我在这里卡了一点>
我的 php 脚本返回此 JSON(在变量响应中)(使用 json_encode 进行编码的数组):
{"1":{"id":"pvv001","tooltip":"tip1","link":"http:\/\/domain\/file1.html"},"2":{"id":"pvv002","tooltip":"tip2","link":"http:\/\/domain\/file2.html"}}
我希望这是有效的 JSON 对象...
然后这里是 JavaScript 函数,它应该获取这个字符串并处理它 - 将“link”的内容加载到 ELEMENT“id”。
function jLinks(idchapter)
{
var url = 'ajax_loadlinks.php';
var data = {
idchapter : idchapter
};
$.post(url,data, function(response)
{
//$('#coursecontent').html(response);
var obj = JSON.parse(response);
for (var i=0; i<obj.length; i+1)
{
$('#'+obj[i].id).html('<a href="'+obj[i].link+'">link</a>');
}
});
}
它不会在浏览器或控制台中抛出任何错误,但元素根本没有更新。
我怀疑我的解析和访问数据是错误的,但我不知道如何调试。
最佳答案
由于您的字符串是一个对象
而不是数组
,所以您需要 $.each循环遍历对象的每个key
的方法。
var obj ={
"1": {
"id": "pvv001",
"tooltip": "tip1",
"link": "http:\/\/domain\/file1.html"
},
"2": {
"id": "pvv002",
"tooltip": "tip2",
"link": "http:\/\/domain\/file2.html"
}
};
$.each(obj,function(i,v){
$('#'+v.id).html('<a href="'+v.link+'">link</a>');
});
<强> Fiddle
关于javascript - AJAX - 解析 JQUERY 中返回的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46584701/