[英]How to loop through a WordPress WP_Query object using jQuery?
我正在将WP_Query
对象传递给我的JavaScript文件中的成功函数,并且在尝试遍历它时遇到问题。
我的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遍历查询对象呢?
尝试像这样遍历它:
for(var i in data) {
if(data.hasOwnProperty(i)) {
console.log(data[i]);
}
}
最好的选择是在jQuery http://api.jquery.com/jquery.getjson/中使用getJSON函数,并像其他任何JavaScript变量一样循环遍历。
例如。
for (var object in data) {
....do stuff
}
我质疑您是否要返回整个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...
}
},...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.