无法在jquery中解析json

时间:2011-09-20 05:19:25

标签: jquery ajax json parsing

我正在使用jquery.parseJSON(),但它没有发生。我正在做的是对服务器进行ajax调用,然后在成功时我尝试使用jquery.parseJSON()解析从服务器获取的数据,但它无效。

function getIdVals(id){
        $.ajax(
            {
                url: "MyServlet",
                data: "Id="+id,
                cache: false,
                success: function(html){
                    alert(html);
                    var obj = jquery.parseJSON(html);
                    alert(obj.data);
                }
            }
        );
    }

我从服务器获得的响应如下所示:

'{ "data" : "{ aas:five,asda:five,alskjaskdakbd:two,test:two,asddas:five,
             lasnd:five,ad:five,this:two,smd:five,alskjaskdakbdals:four,}"}'

当我尝试将上述字符串放在jquery.parseJSON函数中时,它工作正常,但不知道为什么写jquery.parseJSON(html)不起作用。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

你得到的json是有效的,它应该是

{
    "data": {
        "aas": "five",
        "asda": "five",
        "alskjaskdakbd": "two",
        "test": "two",
        "asddas": "five",
        "lasnd": "five",
        "ad": "five",
        "this": "two",
        "smd": "five",
        "alskjaskdakbdals": "four"
    }
}

然后@zerkms回答

function getIdVals(id){
        $.ajax(
            {
                url: "MyServlet",
                data: "Id="+id,
                cache: false,
                dataType: 'json', // <<<<--------
                success: function(json){
                    // work with json here                    
                }
            }
        );
    }

答案 1 :(得分:0)

您可以为请求指定dataType: 'json'属性,而您将在函数中获得已解析的对象

function getIdVals(id){
        $.ajax(
            {
                url: "MyServlet",
                data: "Id="+id,
                cache: false,
                dataType: 'json', // <<<<--------
                success: function(json){
                    // work with json here                    
                }
            }
        );
    }

答案 2 :(得分:0)

你的json不正确。 json中的错误是:

'{ "data" : "{ aas:five,asda:five,alskjaskdakbd:two,test:two,asddas:five,
             lasnd:five,ad:five,this:two,smd:five,alskjaskdakbdals:four,}"}'
  1. 开头和结尾的单引号。
  2. 逗号在结尾处。
  3. 您似乎也希望获得价值的json数据。因此,也可以用引号将值条目换行。
  4. 所以有效的json看起来像是:

    { "data" : { "aas":"five","asda":"five","alskjaskdakbd":"two","test":"two",
                "asddas":"five","lasnd":"five","ad":"five","this":"two","smd":"five",
                "alskjaskdakbdals":"four"}}
    

    尝试从服务器获取这种json。

    至于jquery ajax调用是关注的我不认为如果你只是将这个json字符串作为成功函数的响应并且如果你将这作为响应的一部分得到一些东西然后其他的话,则不需要进行任何更改已经很好地解释了它。


    您对 3nigma的答案的评论

        $.each(obj.data, function(key,val) {
            alert(key+" "+val);
        });