1

我有这样的 url,这是一个 js 文件示例,例如这个链接http://www.mysite.com/json.js 并且该链接将输出一个 json 格式的值,如下所示:

{
"note":null,
"attributes":null,
"total_price":9980,
"total_weight":0,
"item_count":4,
"items":[{
  "id":214597138,
  "title":"Acai +",
  "price":2495,
  "line_price":9980,
  "quantity":4,
  "sku":"",
  "grams":0,
  "vendor":"Delta Labs",
  "variant_id":214597138,
  "url":"/products/acai",
  "image":"http://cdn.shopify.com/s/files/1/0156/4994/products/acai_bottle.png?385",
  "handle":"acai",
  "requires_shipping":true
}],
"requires_shipping":true}

现在我想获取该链接,然后在我的 jquery 上,我将如何使用该链接和 json 输出来获取标题、url、价格、sku 等值?

我在谷歌上搜索是否有一些函数可以处理这个问题,我发现了 jQuery.getJSON,但我不太了解,或者它是否适用于我想要完成的任务?

顺便说一下,http ://www.mysite.com/json.js,它的json值是动态的,所以就是我要抓取的链接,输出json内容

4

4 回答 4

3

这是我的做法,例如在 ajax 请求中。

$.get('http://www.mysite.com/json.js', function(result) {
   var json = $.parseJSON(result);
   alert(json.title); //Do whatever you want here
});
于 2012-05-04T06:12:33.520 回答
1

Make sure your JSON is valid -> http://www.jsonlint.com

To go through every entry in jSON try this:

$.getJSON("url/to/json/file",function(data){
    $.each(data,function(index,element){
        console.log(element.items.url);
    });
});

To get one entry try this (without $.each):

$.getJSON("url/to/json/file",function(data){
    console.log(data.items.url);
});

Make sure it's not a CrossDomain issue! JSON parsing between domains doesn't work in some cases. Make sure it's not one of them. To work with CrossDomain use JSONP. The difference between JSON and JSONP it's that JSONP can support callback and works over crossdomain.

Hope it helps

于 2012-05-04T07:19:37.837 回答
0

把它放在一个变量中假设,

myJSON = $.parseJSON(YOUR_JSON);

然后,

myJSON.items[0].url
于 2012-05-04T06:07:27.863 回答
0

jQuery.parseJSON

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

你也可以使用jQuery.getJSON/

于 2012-05-04T06:08:09.823 回答