0

我正在做一个返回一些 json 数据的 ajax 调用。我需要获取这些数据,遍历它并构建一个新的 javascript 数组。

这是返回的 json 的样子:

{
    query: [ ],
    products: 
[
    
{
    title: "title 1",
    price: "6.00",
    magazine: "magazine name 1",
    image: "/p/c/pc_90_cover.jpg",
    type: "Magazine",
    market: "Technology",
    zinio: "http:www.zinio.com",
    newsstand: "http://www.link1.php"
    },

    
{
    title: "title 2",
    price: "6.00",
    magazine: "magazine name 2",
    image: "/p/c/pc_90_cover.jpg",
    type: "Magazine",
    market: "Technology",
    zinio: "http:www.zinio.com",
    newsstand: "http://www.link2.php"
    },

    
{
    title: "title 3",
    price: "6.00",
    magazine: "magazine name 3",
    image: "/p/c/pc_90_cover.jpg",
    type: "Magazine",
    market: "Technology",
    zinio: "http:www.zinio.com",
    newsstand: "http://www.link3.php"
    }
    ]

}

如何在 javascript 中遍历这些数据?这是我到目前为止所拥有的,但这是非常错误的!- 抱歉,我的 javascript 不是我最强的技能!

                    var allProducts = $.get("http://localhost:8888/imagine-publishing/web/app_dev.php/api/v1/search/search.json?query=pho", function(data) {


                    var arrProducts = [
                        for (var product in allProducts) {

                            title  = product.title,
                            url = product.url, 
                            label = product.title, 
                            magazine = product.magazine,
                            image = product.imageThumb,
                            newsstand = product.newsstand,
                            googleplay = product.googleplay,
                            kindle = product.kindle, 
                            barnesnoble = product.barnesnoble,
                            zinio = product.zinio, 
                            kobo = product.kobo, 
                            waterstones = product.waterstones, 
                            type = product.type, 
                            brandurl = product.brandurl 

                            },

                     ];

                });

                console.log(arrProducts);
4

3 回答 3

4

假设 JSON 使用正确的 Content-Type ( application/json) 提供,jQuery 将自动解析 JSON 并使用结果填充回调函数的第一个参数。

var arrProducts = data.products;
于 2012-10-26T11:55:35.590 回答
1

http://api.jquery.com/jQuery.parseJSON/

jQuery.parseJSON("json string")

于 2012-10-26T11:55:07.540 回答
0

使用 jQuery 的 getJSON

http://api.jquery.com/jQuery.getJSON/

  $.getJSON(url, function(data){
   // Your code goes here
  });
于 2012-10-26T11:58:52.247 回答