用jQuery的$.each方法无法解析WebServers返回的JSON
通过jQuery的Ajax方法获取到WebServers返回的JSON数组,但是通过each方法解析时,获得的数据始终是undefined.
通过FireBug查看返回的数据是正确的,数据内容是:{"d":"[{id:2,Name:\u0027维生素A\u0027,Introduction:\u002712466说\u0027,Time:\u00272012/10/7 19:27:00\u0027}]"} 通过json.d也可以获取到数据,就是使用each方法无法遍历,在遍历的时候,用alert(this),显示的数据和json.d显示的一样,感觉完全没有分拆样
代码如下
Websevers代码
public string NutrientsList() { string result = string.Empty; IList<NutrientsInfo> info = new List<NutrientsInfo>(); info = nut.INutrientsAllList(); if (info.Count < 1) { result = "null"; } else { result = "["; for (int i = 0; i < 1; i++) { result += "{id:" + info[i].ID + ",Name:\'" + info[i].Name + "\',Introduction:\'" + info[i].Introduction + "\',Time:\'" + info[i].CreatTime + "\'}"; result += ","; } result = result.TrimEnd(','); result += "]"; } return result; }
$.ajax({ type: "POST", contentType: "application/json;utf-8", dataType: "json", url: "../CookBook/Nutrients.asmx/NutrientsList", data: "{}", beforeSend: function () { $("#NutrientsList").empty().html("<div style=\"text-align:center\">正在读取菜谱!<\/div>"); }, success: function (result) { if (result == "null") { $("#NutrientsList").empty().html("<div style=\"text-align:center\">没有找到营养素!<\/div>"); } else { var json = eval(result); var html = ""; html += "<table class=\"data-table\" width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\r\n"; html += "<tbody>\r\n"; html += "<tr>\r\n"; html += "<th scope=\"col\"><input value=\"true\" type=\"checkbox\" title=\"全选/不选\" onclick=\"CheckBox.CheckAll(this);\" name=\"CheckAll\" id=\"CheckAll\" /><input value=\"false\" type=\"hidden\" name=\"CheckAll\" /></th>\r\n"; html += "<th scope=\"col\">营养素名称</th>\r\n"; html += "<th scope=\"col\">营养素介绍</th>\r\n"; html += "<th scope=\"col\">创建时间</th>\r\n"; html += "<th scope=\"col\">编辑</th>\r\n"; html += "<th scope=\"col\">删除</th>\r\n"; html += "</tr>\r\n"; $.each(json, function () { html += "<tr>\r\n"; html += "<td class=\"chk\"><input value=\"true\" type=\"checkbox\" rel=\"2\" name=\"CheckBox\" class=\"check-box\" /><input value=\"false\" type=\"hidden\" name=\"CheckBox\" /></td>\r\n"; html += "<td class=\"txt80 c\"><a href=\"#\" title=\"查看资料\">" + this.Name + "</a></td>\r\n"; html += "<td class=\"txt200 c\">" + this.Introduction + "</td>\r\n"; html += "<td class=\"txt80 c\">" + this.Time + "</td>\r\n"; html += "<td class=\"icon\"><a class=\"opt\" title=\"编辑\" href=\"#\"><span class=\"icon-sprite icon-edit\"></span></a></td>\r\n"; html += "<td class=\"icon tail\"><a class=\"opt\" title=\"删除\" href=\"javascript:DeleteById(2);\"><span class=\"icon-sprite icon-delete\"></span></a></td>\r\n"; html += "</tr>\r\n"; alert(this); }); $("#NutrientsList").empty().html(html); } } });