2010-06-22 49 views
2

我正在使用this blog post as a guide,詳細介紹瞭如何使用jText和jTemplates將JSON響應填充到模板中。爲什麼我的JSON響應中的HTML被編碼?

我的問題是,其中一個返回的字段(名爲Description)包含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逃脫,但爲什麼會發生?這裏是jQuery的進行調用的JSON響應:

$.getJSON("<%= Url.Action("List", "Activity") %>", 
    function(data){ 
     $("#aLog").setTemplate($("#templateHolder").html()); 
     $("#aLog").processTemplate(data); 
    }); 

UPDATE

而這正是源看起來在頁面加載完成(查看>頁面源代碼在Firefox),如:

&lt;a href="/en/Yokota/User/Show/Chad"&gt;Chad&lt;/a&gt; updated their ad, &lt;a href="/en/Yokota/Ad/Show/100"&gt;Validation Test Ad Again&lt;/a&gt;, @&lt;a href="/en/Yokota"&gt;Yokota&lt;/a&gt; 

也許是因爲它已接近凌晨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); 
} 
+0

如何動作方法返回的值作爲一個JsonResult可我們看到的代碼 – womp 2010-06-22 17:39:51

+0

是什麼'processTemplate'做 – Gumbo 2010-06-22 17:44:00

+0

@womp我添加了控制器代碼感謝您的快速反應 – Chaddeus 2010-06-22 17:47:18

回答

3

原來,問題出在jTemplates中的設置。 setTemplate行需要爲:

$("#aLog").setTemplate($("#templateHolder").html(), [], {filter_data: false}); 

特別是,必須將filter_data設置爲false。默認jTemplates html編碼。 ;?(

0

在UTF8作出這樣的檢查中的示例用 「的contentType」 your example

 $.ajax({ 
       type:"GET", 
       url: "<%= Url.Action("List", "Activity") %>", 
       data: "{}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function(data){ 
        $("#aLog").setTemplate($("#templateHolder").html()); 
        $("#aLog").processTemplate(data); 
       } 
      }); 
     }); 
+0

這是我寫它的原始方式,同樣的問題。 – Chaddeus 2010-06-22 17:51:51

+0

您確定服務器在請求中接受* application/json *嗎? – Gumbo 2010-06-22 18:05:17

0

的JSONSerializer與自動逸出 「<」 和 「>」 的字符unicode轉義序列。

jQuery應該能夠正常解析這些。您正在使用$ .getJSON方法,我認爲它會自動將響應評估爲json和unescape它,所以我有點難以理解爲什麼最終輸出仍包含轉義代碼。

如果你這樣做:

$("#aLog").processTemplate(eval("(" + data+ ")")); 

這是否解決了問題?

+0

它沒有,但感謝有關JSONSerializer自動轉義HTML實體的信息。 – Chaddeus 2010-06-25 00:35:40

相關問題