我在用方括号中包含的一些JSON数据进行AJAX请求时遇到了麻烦-值返回undefined
。
我已经测试了第二个JSON文件,没有方括号工作得很好,但没有它们,所以我知道这绝对是问题。
问题是我在哪里进行更改:在JSON中还是在AJAX请求中?
这是我的PHP代码片段,它创建了这个JSON文件。
foreach ($product_urls as $i => $product_url) {
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
这是我的AJAX请求:
$('#container').html('<h3 class="feeds-loader text-muted" style="text-align: center;">Loading...</h3>');
$.ajax({
url: 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type: 'GET',
dataType: 'json',
success: function(result) {
$('#container').html('');
var product_url = result['product_url'];
var shop_name = result['shop_name'];
var photo_url = result['photo_url'];
var was_price = result['was_price'];
var now_price = result['now_price'];
alert(product_url);
},
error: function() {
alert("error");
}
})
});
foreach ($product_urls as $i => $product_url) { $result[] =...
$result
是一个行数组,因此在success: function(result)
中result
是一个行数组,而不是单行。
这将显示一个URL
var product_url = result[0]['product_url'];
我猜你想迭代它们?
$('#container').html('');
for (i in result){
var product_url = result[i]['product_url'];
var shop_name = result[i]['shop_name'];
var photo_url = result[i]['photo_url'];
var was_price = result[i]['was_price'];
var now_price = result[i]['now_price'];
alert(product_url);
}
试试用这个:
array_push($result, array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
));
代替$result[]?