淺談返回值型別: json與html
返回json時要注意的一些東西:
1、後臺千萬不要用StringBuilder的AppendLine()方法, 這樣會夾雜進去"\r\n", 而不能成功;
2、json是脆弱的, 如果要構建html作為其中的一個值, 而html中又有單雙引號, 那麼在後臺最好是這樣:
sb.Replace("\"","%db%");
sb.Replace("'", "%single%");
strAjaxHtml = string.Format("{{\"count\":\"{0}\",\"html\":\"{1}\"}}", DT.Rows.Count.ToString(), sb.ToString());
前臺:
String.prototype.replaceAll = function (s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2);
}
$.post("reg.aspx", search, function (data) {
$("#spanCount").html(data);
var obj = eval('(' + data + ')');
obj.html = obj.html.replaceAll("%single%", "'").replaceAll("%db%", "\"");
$("#spanCount").html(obj.count);
$("#tbodyList").html(obj.html);
});
反正最好是要兩次替換;
==============================================
而html則不一樣了, 非常的寬容與簡單。不需要管單引號與雙引號。
後臺, 建立html直接sb.Append("");
strAjaxHtml =string.Format("{0}|~|{1}",DT.Rows.Count.ToString(),sb.ToString());
前臺:
$.post("reg.aspx", search, function (data) {
var arr = data.split("|~|");
$("#spanCount").html(arr[0]);
$("#tbodyList").html(arr[1]);
});
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
總結:
一般情況下最好是用html;
如果一定要用json, 那最好不要在後臺直接構建html, 構建的事情要放在前臺才能減少出錯的可能。