如何从返回json数组的ajax调用构建一个javascript数组?

时间:2012-10-26 11:53:24

标签: javascript ajax arrays json loops

我正在进行一个返回一些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);

3 个答案:

答案 0 :(得分:4)

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

var arrProducts = data.products;

答案 1 :(得分:1)

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

jQuery.parseJSON("json string")

答案 2 :(得分:0)

使用jQuery的getJSON

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

  $.getJSON(url, function(data){
   // Your code goes here
  });