2011-12-21 70 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格式正確,然後再擔心解析。