2014-09-05 70 views
2

我將一個WP_Query對象傳遞給JavaScript文件中的成功函數,並且在試圖循環它時遇到問題。如何通過使用jQuery的WordPress WP_Query對象循環?

我的PHP:

$args = array(
    'post_type' => 'post' 
); 
$query = new WP_Query($args); 

// Pass the $query object to the success function in my script. 
echo json_encode($query); 

在我的劇本我的成功函數:

success: function(data) { 
    // I'd like to loop through the query object here. 
},... 

我知道如何通過WP_Query對象服務器端循環:

if ($query->have_posts()) { 
    while ($query->have_posts()) { 
     $query->the_post(); 
     echo get_the_title(); 
    } 
} 

但如何我可以在我的腳本中使用jQuery成功函數中循環查詢對象嗎?

回答

1

嘗試迭代它像這樣:

for(var i in data) { 
    if(data.hasOwnProperty(i)) { 
    console.log(data[i]); 
    } 
} 
+0

感謝您的想法,我會試試看... – henrywright 2014-09-05 17:50:24

+0

無後顧之憂。讓我知道你是怎麼辦的。 – ornous 2014-09-05 17:51:04

1

最好的辦法是使用的getJSON功能的jQuery http://api.jquery.com/jquery.getjson/和遍歷像任何其他JavaScript變量。

例如。

for (var object in data) { 
    ....do stuff 
} 
+1

獲取對象不是問題。在我的成功函數'data'裏面保存對象。我的問題正在循環。我很好用PHP,但是對jQuery來說是新手 – henrywright 2014-09-05 17:47:23

+1

@henrywright是的,但是重要的是你使用該返回做了什麼,getJSON將解碼創建對象的JSON字符串。使用jQuery.ajax並不總是這種情況。 – 2014-09-05 17:50:21

+0

好的,謝謝你的提示,我會研究解碼字符串 – henrywright 2014-09-05 17:51:22

1

我問你是想要返回整個WP_Query對象,還是僅僅查詢結果(posts屬性)。我建議的方法是:

$args = array(
    'post_type' => 'post' 
); 
$query = new WP_Query($args); 

// Pass the $query object to the success function in my script. 
echo json_encode($query->posts); 

...在jQuery的:

success: function(data) { 
    for(var i in data) { 
     var post = data[i]; 
     // Do something with post object here... 
    } 
},... 
+0

感謝這個例子,賈斯汀。關於'post'對象,假設我想訪問post title屬性,我會這樣做嗎?'post.post_title'?參考:http://codex.wordpress.org/Function_Reference/$post – henrywright 2014-09-05 22:53:11

+0

是的,這是WordPress的$ post對象的序列化版本。您將不會收到原生WP功能的一些好處,例如get_content()包裝段落或get_permalink()生成鏈接的方式,但您將獲得在數據庫中表示的對象。 – 2014-09-08 02:14:52