我正在使用this blog post as a guide ,详细介绍了如何使用 jQuery 和 jTemplates 将 JSON 响应填充到模板中。
我的问题是,返回的字段之一(名为“描述”)包含 HTML,但 HTML 括号被编码为\u003C 和\u003e。
这是服务器返回的 HTML(在描述字段中):
<a href="/en/Yokota/User/Show/Chad">Chad</a> updated their ad, <a href="/en/Yokota/Ad/Show/100">Validation Test Ad Again</a>, @<a href="/en/Yokota">Yokota</a>
JSON 响应如下所示:
[{"TypeOfActivity":"0","Description":"\u003ca href=\"/en/Yokota/User/Show/YokotaTour\"\u003eYokotaTour\u003c/a\u003e posted \u003ca href=\"/en/Yokota/Ad/Show/166\"\u003eOne of the best for sure\u003c/a\u003e for sale @\u003ca href=\"/en/Yokota\"\u003eYokota\u003c/a\u003e","DateHappened":"6/23/2010 12:26:55 AM"}]
注意“\u003c”或“\u003e”。这些看起来像是 unicode 转义,但为什么会发生这种情况呢?这是调用 JSON 响应的 jQuery:
$.getJSON("<%= Url.Action("List", "Activity") %>",
function(data){
$("#aLog").setTemplate($("#templateHolder").html());
$("#aLog").processTemplate(data);
});
更新
这就是页面加载完成后源代码的样子(在 Firefox 中查看 > 页面源代码):
<a href="/en/Yokota/User/Show/Chad">Chad</a> updated their ad, <a href="/en/Yokota/Ad/Show/100">Validation Test Ad Again</a>, @<a href="/en/Yokota">Yokota</a>
也许是因为时间已接近凌晨 3 点,但我很困惑......非常感谢任何帮助 - 谢谢!
更新2
public JsonResult List()
{
IList<ActivityContract> contracts = new List<ActivityContract>();
var activityList = _db.Activity.ByBaseID(CurrentBase.BaseID).OrderByDescending(a => a.DateHappened);
foreach (var a in activityList) {
contracts.Add(new ActivityContract { TypeOfActivity = a.TypeOfActivity.ToString(), Description = a.Description, DateHappened = a.DateHappened.ToString() });
}
return Json(contracts, JsonRequestBehavior.AllowGet);
}
最佳答案
事实证明,问题出在 jTemplates 中的设置上。 setTemplate 行需要是这样的:
$("#aLog").setTemplate($("#templateHolder").html(), [], {filter_data: false});
特别是,filter_data 必须设置为 false。默认情况下 jTemplates html 编码。 ;(
关于c# - 为什么 JSON 响应中的 HTML 会被编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3095621/