这是我对服务器的JSON响应: -
{
"Details": [
{
"ID": 234872,
"Name": "asdfg",
"Address": "hasgdkjfgsjaf,asfuysdfg",
"Email": "",
"Mobile": "",
"Profile": "gwekjrg ",
"Amt": 0,
"Date": ""
}
]
}
这是我编写的js代码,用于解析它并在我的应用程序中使用它: -
function getDetail(madeUrl) {
$.ajax({
url: madeUrl,
type : "GET",
dataType : "json",
contentType: "application/json",
success: function(msg) {
$("#detail tr").remove();
var searchResponse = msg.Details;
var html;
$.each(searchResponse, function(index, data) {
html = '<tr><td>' + data.Name + '</td> <td>' + data.Amt + '</td></tr>' + data.Profile + '</td></tr>' + data.Date + '</td></tr>';
$("#detail").append(html);
});
$('#report').fadeIn();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("errorstatus: " + xhr.status + " ajaxoptions: " + ajaxOptions + " throwError: " + thrownError);
},
complete : function() {
}
});
}
但它会抛出一个错误,就像无法解析JSON字符串。无法找出原因。有什么帮助吗?
答案 0 :(得分:0)
请尝试此代码。它对我来说很好。希望它对你有所帮助。请告诉我。感谢。
<强> HTML 强>
<div id="detail"></div>
<强>脚本:强>
var j ='{"Details": [{"ID": "234872","Name": "asdfg","Address": "hasgdkjfgsjaf,asfuysdfg","Email": "","Mobile": "","Profile": "gwekjrg ","Date": ""}]}';
var json = $.parseJSON(j).Details;
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
$("#detail").append(k+" : "+ v + " <br />");
});
});
演示网址:
答案 1 :(得分:0)
如果您有不可解析的JSON消息,则意味着JQuery不会将您的JSON视为有效。
可以肯定的是,我会从ajax调用中删除dataType和contentType(默认数据类型为“Intelligent Guess”,这意味着jquery会在检测到它时自动解析JSon,否则发送文本)并在开头添加以下行成功的功能:
alert(msg === Object(msg)?"json received:\n"+JSON.stringify(msg):"text received:\n"+msg);