簡體   English   中英

有沒有辦法使用jquery解析此json

[英]Is there a way to parse this json using jquery

有沒有一種方法可以使用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);

有人能幫助我嗎!

我認為您可能應該以不同的方式構建數據。

$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
    });
});

您可以嘗試parseJSON:

jQuery.parseJSON();

jQuery確實具有jQuery.parseJSON

或者,您可以僅將“ JSON.parse()”與json2.js結合使用, 作為不原生支持此功能的瀏覽器的備用。

parseJSON()-http: //jsfiddle.net/VHpLp/

是的,要在客戶端/瀏覽器上解析JSON,請使用:

 var jsonObj = JSON.parse(yourJsonString);

如果您嘗試在客戶端解析JSON字符串,則jQuery可以使用,語法為:

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

API jQuery-jQuery.parseJSON()

如果要在服務器端解析它,語法和工具將取決於您使用的JSON庫。 我不熟悉PHP,所以我不知道那里有什么可用。

旁注 -在擔心解析之前,請確保JSON格式正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM