在wordpress中使用ajax返回JSON数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17982078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning JSON data with ajax in wordpress
提问by andy
Ok so a fairly long question here. I'm fairly new to AJAX and especially using it in the context of WordPress, but I've been following along some tutorials online and I think I'm almost there.
好的,这是一个相当长的问题。我对 AJAX 相当陌生,尤其是在 WordPress 的上下文中使用它,但我一直在关注一些在线教程,我想我快到了。
I'll paste what I have so far and explain my thinking.
我将粘贴到目前为止的内容并解释我的想法。
Ok so to start, the JS.
好的,开始,JS。
jQuery(document).ready(function(){
jQuery('.gadgets-menu').mouseenter(function(){
doAjaxRequest();
});
});
Mouse enters .gadgets-menu and the request triggers, using mouseenter so it fires once.
鼠标进入 .gadgets-menu 并触发请求,使用 mouseenter 使其触发一次。
The request itself.
请求本身。
function doAjaxRequest(){
// here is where the request will happen
jQuery.ajax({
url: 'http://www.mysite.com/wp-admin/admin-ajax.php',
data:{
'action':'do_ajax',
'fn':'get_latest_posts',
'count':5
},
dataType: 'JSON',
success:function(data){
//Here is what I don't know what to do.
},
error: function(errorThrown){
alert('error');
console.log(errorThrown);
}
});
}
Now the php function.
现在是php函数。
add_action('wp_ajax_nopriv_do_ajax', 'our_ajax_function');
add_action('wp_ajax_do_ajax', 'our_ajax_function');
function our_ajax_function(){
switch($_REQUEST['fn']){
case 'get_latest_posts':
$output = ajax_get_latest_posts($_REQUEST['count']);
break;
default:
$output = 'No function specified, check your jQuery.ajax() call';
break;
}
$output=json_encode($output);
if(is_array($output)){
print_r($output);
}
else{
echo $output;
}
die;
}
And the ajax_get_latest_posts function
和 ajax_get_latest_posts 函数
function ajax_get_latest_posts($count){
$posts = get_posts('numberposts='.'&category=20'.$count);
return $posts;
}
So, if I've done this right the output should be $posts = get_posts('numberposts='.'&category=20'.$count);ie. the number of posts (5), from category 20.
I don't know what to do with that now, how do I get the title and the thumbnail?
所以,如果我做对了,输出应该是$posts = get_posts('numberposts='.'&category=20'.$count);ie。帖子数 (5),来自第 20 类。我现在不知道该怎么办,如何获得标题和缩略图?
I'm sorry if this is silly, I'm just fumbling around here.
对不起,如果这是愚蠢的,我只是在这里摸索。
Amended php
修改php
add_action('wp_ajax_nopriv_do_ajax', 'our_ajax_function');
add_action('wp_ajax_do_ajax', 'our_ajax_function');
function our_ajax_function(){
$output = ajax_get_latest_posts($_REQUEST['count']); // or $_GET['count']
if($output) {
echo json_encode(array('success' => true, 'result' => $output));
}
else {
wp_send_json_error(); // {"success":false}
// Similar to, echo json_encode(array("success" => false));
// or you can use, something like -
// echo json_encode(array('success' => false, 'message' => 'Not found!'));
}
$output=json_encode($output);
if(is_array($output)){
print_r($output);
}
else{
echo $output;
}
die;
}
function ajax_get_latest_posts($count)
{
$args = array( 'numberposts' => $count, 'order' => 'DESC','category' => 20 );
$post = wp_get_recent_posts( $args );
if( count($post) ) {
return $post;
}
return false;
}
This does not work.
这不起作用。
jQuery(document).ready(function(){
jQuery('.gadgets-menu').mouseenter(function(){
doAjaxRequest();
});
});
function doAjaxRequest(){
// here is where the request will happen
jQuery.ajax({
url: 'http://localhost:8888/wp-admin/admin-ajax.php',
data:{
'action':'do_ajax',
'fn':'get_latest_posts',
'count':5
},
dataType: 'JSON',
success:function(data){
if(data.success) {
alert("It works");
}
else {
// alert(data.message); // or whatever...
}
}
});
}
No alert is shown.
不显示警报。
回答by The Alpha
In your code get_posts('numberposts='.'&category=20'.$count);is wrong, but you can use wp_get_recent_postsfunction instead (though it uses get_postsanyway), for example
在您的代码中get_posts('numberposts='.'&category=20'.$count);是错误的,但是您可以改用wp_get_recent_posts函数(尽管它仍然使用get_posts),例如
function ajax_get_latest_posts($count)
{
$args = array( 'numberposts' => $count, 'order' => 'DESC','category' => 20 );
$post = wp_get_recent_posts( $args );
if( count($post) ) {
return $post;
}
return false;
}
Then in your our_ajax-functionyou can use
然后在our_ajax-function你可以使用
$output = ajax_get_latest_posts($_REQUEST['count']); // or $_GET['count']
if($output) {
echo json_encode(array('success' => true, 'result' => $output));
}
else {
wp_send_json_error(); // {"success":false}
// Similar to, echo json_encode(array("success" => false));
// or you can use, something like -
// echo json_encode(array('success' => false, 'message' => 'Not found!'));
}
In you successcallback function, you can then check
在你的success回调函数中,你可以检查
success:function(data){
if(data.success) {
// loop the array, and do whatever you want to do
$.each(data.result, function(key, value){
// you can use $(this) too
// console.log($(this)); // check this for debug and get an idea
});
}
else {
// alert(data.message); // or whatever...
}
}
You can read hereabout wp_send_json_errorhelper function to learn more about helper functions.
您可以在此处阅读有关wp_send_json_error辅助函数的信息,以了解有关辅助函数的更多信息。
Update :
更新 :
Also remember that, after $output=json_encode($output);the $outputis not an array anymore, instead, it's a jsonstring, so is_array($output)will return false but if you use is_array()just before you encode it using $output=json_encode($output);like
还记得那之后$output=json_encode($output);的$output是不是一个数组了,相反,它是一个json字符串,所以is_array($output)会返回错误,但如果你使用的is_array()只是你使用编码前$output=json_encode($output);像
if( is_array( $output ) ) {
$output = json_encode( $output );
}
In this case, is_array( $output )will return true.
在这种情况下,is_array( $output )将返回true。

