简体   繁体   English

无法解析JSON字符串

[英]Unable to parse JSON string

this is my JSON response from server :- 这是来自服务器的JSON响应:-

{
    "Details": [
        {
            "ID": 234872,
            "Name": "asdfg",
            "Address": "hasgdkjfgsjaf,asfuysdfg",
            "Email": "",
            "Mobile": "",
            "Profile": "gwekjrg ",
            "Amt": 0,
            "Date": ""
        }
    ]
}

this is my js code that i have written to parse it and use it in my app :- 这是我编写的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() {

            }
        });
}

but it throws an error like unable to parse JSON string.Unable to find out the reason.Any help ? 但这会引发错误,例如无法解析JSON字符串。无法找出原因。有帮助吗?

Please try this code. 请尝试此代码。 It's working fine for me. 对我来说很好。 Hope it should helpful for you. 希望对您有帮助。 Please let me know. 请告诉我。 Thanks. 谢谢。

Html: HTML:

<div id="detail"></div>

Script: 脚本:

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 />");
});
});

Demo URL: 演示网址:

Demo 演示版

If you have unparsable JSON message, it means that somehow your JSON is not seen as valid by JQuery. 如果您有无法解析的JSON消息,则意味着JQuery无法将您的JSON视为无效。

To be sure, I would remove dataType and contentType from the ajax call (default datatype is "Intelligent Guess" which means jquery will automatically parse JSon if it detects it or send text otherwise) and add the following line at the begining of the success function : 可以肯定的是,我将从ajax调用中删除dataType和contentType(默认数据类型为“ Intelligent Guess”,这意味着jquery如果检测到它会自动解析JSon或发送文本),并在成功函数的开头添加以下行:

alert(msg === Object(msg)?"json received:\n"+JSON.stringify(msg):"text received:\n"+msg);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM