jQuery的解析不正确的JSON [英] jQuery not parsing JSON properly

查看:134
本文介绍了jQuery的解析不正确的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。我建了一个脚本,以请求发送回一个响应内部链接。这是脚本的样子:

I have a problem. I built a script to make a request to an internal link that sends back a response. This is what the script looks like:

jQuery.get(callUrl, function(data){
              console.log(typeof data);
              jQuery.each(data.items, function(i,item){            

                                      console.log(i);

                                });
        },'json');

和服务器发回的响应是这样的:

and the response that the server sends back looks like this:

{"items":[            
  {
   "src": "gallery_item_data_Jc4EaLP6vlwd_large.jpg",
   "id": "83",
   "gallery_id": "30",
   "username": "admin"
  }]
}

我的问题是,当我分析的数据的类型始终是字符串。我需要为它是一个对象,这样我可以查询它和我的脚本解析它。为了找到问题的底部,我试过在jQuery的文档页面比较我的脚本的例子:

My problem is when I parse the "data" its type is always string. I need for it to be an object so that I can query it and parse it with my script. To get to the bottom of the problem, I've tried comparing my script to the example on jQuery's documentation page:

http://docs.jquery.com/Ajax/jQuery.getJSON

这个页面上的请求和我的请求,主要区别是,它采用了的getJSON方法。当我试图使用的URL到我的服务器,我已经变得没有反应可言,所以这是主要的原因,我选择了GET方法,并指定返回类型为json的。

The main differences with the request on this page and my request is that it uses the getJSON method. When I tried to use that with the url to my server, I have gotten no response at all, so that is the main reason I opted for the get method, and specifying the return type as "json."

另一件事我想:我检查了<一href="http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?"相对=nofollow> Flickr的饲料是jQuery的示例使用寻找它发回,想也许我进了错误的报头中的Content-type头,而正是这种对Flickr的饲料:

Another thing I tried: I checked out the Flickr feed that the jQuery example uses to look for the Content-type header that it sends back, thinking maybe my feed had the wrong header, and it is this on the Flickr feed:

Content-Type    application/x-javascript; charset=utf-8

这正是我自己的饲料相同的标题。所以,我觉得很奇怪。没有人知道为什么会这样?

This is exactly the same header on my own feed. So I am puzzled. Does anyone know why this is happening?

推荐答案

的JSON需要有它周围的支架,所以它应该是:

The JSON needs to have brackets around it, so it should be:

({"items":[            
  {
   "src": "gallery_item_data_Jc4EaLP6vlwd_large.jpg",
   "id": "83",
   "gallery_id": "30",
   "username": "admin"
  }]
})

您应该然后能够使用的getJSON,因为这是获得的数据作为对象的最简单方法。不过,你也可以的eval()的字符串,这将返回一个对象。

You should then be able to use getJSON, as this is the easiest way to get the data as an object. However, you can also eval() the string and that will return an object.

这篇关于jQuery的解析不正确的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆