簡體   English   中英

使用Jquery從JSON格式中提取數據

[英]Pull Data from JSON format using Jquery

我有這樣的URL,這是一個像這個鏈接http://www.mysite.com/json.js的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輸出的鏈接以獲得標題,網址,價格,sku等值?

我搜索谷歌是否有一些功能可以處理這個,我發現了jQuery.getJSON,但我真的不明白或者它是否適用於我想要完成的事情?

順便說一句, http ://www.mysite.com/json.js,它的json值是動態的,因此它是我想要抓取的鏈接,並輸出json內容

這是我如何做的,例如在ajax請求中。

$.get('http://www.mysite.com/json.js', function(result) {
   var json = $.parseJSON(result);
   alert(json.title); //Do whatever you want here
});

確保您的JSON有效 - > http://www.jsonlint.com

要瀏覽jSON中的每個條目,請嘗試以下操作:

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

要獲得一個條目,請嘗試此操作(不使用$ .each):

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

確保它不是CrossDomain問題! 域之間的JSON解析在某些情況下不起作用。 確保它不是其中之一。 要使用CrossDomain,請使用JSONP。 JSON和JSONP之間的區別在於JSONP可以支持回調並適用於跨域。

希望能幫助到你

把它放在一個變量中,

myJSON = $.parseJSON(YOUR_JSON);

然后,

myJSON.items[0].url

jQuery.parseJSON

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

你也可以使用jQuery.getJSON /

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM