json响应用javascript解析

时间:2011-04-14 14:28:25

标签: jquery json parsing

例如json响应是这样的:

{testing:[
    {"title":"Hello","text":"Hello Test!"},
    {"title":"World","text":"World Test!"}
]}

如何使用jQuery getJSON和jQuery.each函数解析此json数据,以便在单独的div标签中打印此数据

2 个答案:

答案 0 :(得分:0)

$的getJSON();期望数据格式正确,所以如果你使用php,你需要使用json_encode($array)

你应该没事,你不需要解析任何东西。

答案 1 :(得分:0)

我认为这可能有效。它调用服务器为你的json然后遍历测试数组并显示内容。

var data = {id: userId}; //Use null if your server needs no info
jQuery.getJSON( "/mylink/getjson", data, function(json){
    if(typeof(json.testing) != "undefined"){
        $(json.testing).each(function(){
            document.write(this.title);
            document.write(this.text);
        });
    }
})
相关问题