JQuery.Cookie を使用して、javascript オブジェクトを Cookie 値として保存しています。
var refinerData = {};
// Read in the current cookie if it exists:
if ($.cookie('RefinerData') != null) {
refinerData = JSON.parse($.cookie('RefinerData'));
}
// Set new values based on the category and filter passed in
switch(category)
{
case "topic":
refinerData.Topic = filterVal;
break;
case "class":
refinerData.ClassName = filterVal;
break;
case "loc":
refinerData.Location = filterVal;
break;
}
// Save the cookie:
$.cookie('RefinerData', JSON.stringify(refinerData), { expires: 1, path: '/' });
firebug でデバッグすると、cookie 値の値が正しくフォーマットされているように見えます。
{"Topic":"病気の予防と管理","Location":"Hatchery Hill Clinic","ClassName":"糖尿病ですが、何を食べればよいですか?"}
Cookie を読み取って解析する SharePoint Web パーツを C# で作成しています。
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["RefinerData"];
if (cookie != null)
{
string val = cookie.Value;
// Deserialize JSON cookie:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var refiners = serializer.Deserialize<Refiners>(cookie.Value);
output.AppendLine("Deserialized Topic = " + refiners.Topic);
output.AppendLine("Cookie exists: " + val);
}
}
私はシリアル化するための Refiners クラスを持っています:
public class Refiners
{
public string Topic { get; set; }
public string ClassName { get; set; }
public string Location { get; set; }
}
ただし、このコードは「無効な JSON プリミティブ」エラーをスローします。これが機能しない理由がわかりません。1 つの可能性は、Cookie を正しく読み取っていないことです。Cookie の値を文字列として出力すると、次のようになります。
%7B%22Topic%22%3A%22Disease%20Prevention%20and%20Management%22%2C%22Class%22%3A%22Childbirth%20%26%20Parenting%202013%22%2C%22Location%22%3A%22GHC%20East %20クリニック%22%7D