简体   繁体   English

我无法解析Jquery ajax JSON响应

[英]I can't parse a Jquery ajax JSON response

I am trying to parse the JSON results from an AJAX call, but do to the limitations of the server I am only able to get one large string. 我试图解析来自AJAX调用的JSON结果,但是对服务器的限制我只能得到一个大字符串。 There are several elements returned, but the data I need to consume is all thrown into a single element. 返回了几个元素,但我需要消耗的数据都被抛入一个元素中。 Now here is the tricky thing... if I use firebug the response has a JSON tag and everything looks like a proper JSON object, but when I try to map or view the results using an alert I notice they are single quotes instead of double quotes. 现在这里是棘手的事情...如果我使用firebug,响应有一个JSON标记,一切看起来像一个正确的JSON对象,但当我尝试使用警报映射或查看结果时,我注意到它们是单引号而不是双引号引号。 i've tried replacing the quotes to no avail as well. 我试过更换报价也无济于事。 I'm pretty much stumped at this point. 在这一点上我非常难过。

the alert would print out something simular to this: [{'id':'2663','parent':'2663'},{'id':'2664','parent':'2664'},]

        $.ajax({
            url: myURL,
            type: 'GET',
            dataType: "json",
            complete: function(docData) {
                var docResults = docData.responseText;
                alert(docResults);
                $(docResults).each(function(i,val){
                    $.each(val,function(k,v){
                          console.log(k+" : "+ v);     
                    });
                });                
            }
        });

The correct way to fix this is to fix it on the server, however, there is a way to fix it client-side using the dataFilter callback. 解决此问题的正确方法是将其修复在服务器上,但是,有一种方法可以使用dataFilter回调来修复客户端。

$.ajax({
  url: myURL,
  type: 'GET',
  dataType: "json",
  dataFilter: function(response) {

    // *** Note: this will have to be modified if quotes 
    // *** can be contained within the data. It doesn't appear as though
    // *** that is the case with the data you have provided. 

    return response
      // fix trailing comma
      .replace("},]","}]")
      // fix quotes
      .replace(/'/g,'"'));
  },
  success: function (response) {
    $.each(response,function(){
      console.log(this);
    });
  }
});

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

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