【问题标题】:Jquery parsing response from api bbyopenJquery解析来自api bbyopen的响应
【发布时间】:2013-03-21 02:34:55
【问题描述】:

我无法从这个 api 进行解析。你能看到我做了什么吗?

PHP 卷曲调用:

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
$options = array(CURLOPT_URL => 'http://api.remix.bestbuy.com/v1/products(salePrice<='.$dollars.'&type=Music)?apiKey=gzunxsecretsdssf444&format=json&show=name,salePrice,shortDescription,image',
                 CURLOPT_HEADER => false,
                 CURLOPT_RETURNTRANSFER => 1
                );

curl_setopt_array($ch, $options);

// grab URL and pass it to the browser
echo curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch); 

js:

$.ajax({
           url: "./file.php",
           type: 'GET',
            dataType: 'JSON',
           success: function (data) {
                console.log("Success");
                console.log(data);
                for(var i=0;i<=data.products.length;i++)
                {
                    var thumb=data.products[i].image;
                    $('<div class="product" style="background-color:green"><a href=""><img src="'+ thumb +'" alt""/></a></div>').appendTo('#find_stuff_div');
                }
            }
           });

var thumb=data.products[i].image;是我遇到麻烦的地方。对象本身记录(显然是 json),但 var thumb 返回“未捕获的类型错误:无法读取未定义的属性‘图像’”。有什么想法吗?

控制台日志

【问题讨论】:

  • 什么是data.products 是一个数组
  • 另外添加一个console.log(data.products, data.products.length)
  • 我从上面的控制台添加了结果

标签: php javascript jquery json curl


【解决方案1】:

您需要对返回的数据调用JSON.parse() 才能将其用作对象。

【讨论】:

    【解决方案2】:

    对不起,你的 for 循环是错误的

    for(var i=0;i<data.products.length;i++)
    

    数组索引从0开始到length - 1,所以你的条件应该是i&lt;data.products.length而不是i&lt;=data.products.length

    【讨论】:

    • 这应该与 var thumb=data.products[i].image; 没有任何关系虽然没有价值。
    • 是的,当i 的值变成data.products.length 即10 时,data.products[10] 是未定义的,因为data.products 的索引是0..9 而不是0..10
    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 2014-01-21
    • 2017-06-14
    • 1970-01-01
    • 2015-04-03
    • 2011-04-30
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多