2011-12-21 41 views
0

有没有一种方法来解析这个使用jQuery?有没有办法解析这个json使用jquery

{"post_title":["car1","car2","car3"],"guid":["http:\/\/car1\/body\/fiat\/","http:\/\/car2\/body\/fiat\/","http:\/\/car3\/body\/fiat\/"]} 

$.getJSON($theUrl, function(data){ 
     var myData = []; 
     $.each(data, function(i, item) { 
      console.log(item[0]); 
      myData.push("<li><a href="+item+">" + item+ "</a></li>"); 
     }); 

PHP代码:

$s = array(); 
while (have_posts()) : the_post(); 
    $s['post_title'][] = get_the_title(); 
    $s['guid'][] = get_permalink(); 
endwhile; 
echo json_encode($s); 

有人可以帮我请!

+2

什么是您所遇到的问题? – jzila 2011-12-21 22:37:19

+1

也许这是一个错字,但你没有关闭你的'数据'功能。 – Purag 2011-12-21 22:38:46

+1

看起来您应该以不同方式构建数据。 [{“post_title”:“car1”,guid:“汽车1的指导”},{“post_title”:“car2”,“guid”:“...”}]。 – Corbin 2011-12-21 22:38:58

回答

2

我想你或许应该建立不同的数据。

$s = array(); 
while (have_posts()) : the_post(); 
    $s['post_title'][] = get_the_title(); 
    $s['guid'][] = get_permalink(); 
endwhile; 
echo json_encode($s); 

可能应:

$s = array(); 
while (have_posts()) : the_post(); 
    $s[] = array(
     'post_title' => get_the_title(), 
     'guid' => get_permalink(), 
    );  
endwhile; 
echo json_encode($s); 

那么你的JS看起来是这样的:

$.getJSON($theUrl, function(data){ 
    $.each(data, function(i, item) { 
     //item.post_title 
     //item.guid 
    }); 
}); 
+0

很高兴我可以帮助:)。另外,在挑剔的一面注意:我不确定它们是自定义书写的,还是某种论坛的一部分,但隐藏在the_post中的全局滥用,get_the_title和get_permalink类型让我感到畏缩。阅读它是没有意义的。 the_post()以某种方式引发下一篇文章被两个独立的函数读取。 – Corbin 2011-12-21 22:51:01

0

雅,对客户端/浏览器解析JSON,使用:

var jsonObj = JSON.parse(yourJsonString); 
1

你可以尝试parseJSON:

jQuery.parseJSON(); 
0

如果你试图解析在客户端的JSON字符串,jQuery将工作和语法是:

var obj = jQuery.parseJSON('{"name":"John"}'); 
alert(obj.name === "John"); 

API jQuery - jQuery.parseJSON()

如果你试图解析它在服务器上语法和工具将取决于您正在使用的JSON库。我不熟悉PHP,所以我不知道那里有什么。

附注 - 确保您的JSON格式正确,然后再担心解析。