我正在尝试在javascript中显示PHP curl json数组数据。
如果我回应
// curl output
$response = curl_exec($curl);
echo $response;
我将以下面的格式将此数据作为输出
{"items":[{"id":"1","food":"rice","Amount":"100","condition":"paid"},
{"id":"2","food":"beans","Amount":"200","condition":"paid"},
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}
问题是如何在Javascript中显示数据?
我已尝试过以下代码但遇到错误“Undefine
”。
有人可以帮帮我吗?
以下是我在Javascript中输出的代码。
function loadData(){
$.post('json.php',
function(response){
$.each(JSON.parse(response),
function(i,v){
$('.info').append('<li><div class="msg-lhs"><span>'+v.id+'</span> <span>'+v.food+'</span> <span>'+v.Amount+'</span> <span>'+v.condition+'</span></div></li>');
});
$('.info').animate({scrollTop: $('.info').prop("scrollHeight")}, 500);
});
答案 0 :(得分:0)
我不知道什么是你的代码真的搞砸了,但我提出了一个稍微不同的方法,工作正常。
注意:假设您正在从curl
请求中获取数据。
只是在循环迭代之外解析你的结果并使用forEach
循环。
var response = '{"items":
[{"id":"1","food":"rice","Amount":"100","condition":"paid"},\
{"id":"2","food":"beans","Amount":"200","condition":"paid"},\
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},\
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},\
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}';
var parsed = JSON.parse(response)
parsed.items.forEach(function(v) {
$('.info').append('<li><div class="msg-lhs"><span>'+v.id+'</span>
<span>'+v.food+'</span> <span>'+v.Amount+'</span>
<span>'+v.condition+'</span></div></li>');
});
$('.info').animate({scrollTop: $('.info').prop("scrollHeight")}, 500);
这是fiddle