Возврат данных JSON с помощью AJAX в WordPress
Итак, довольно длинный вопрос здесь. Я довольно новичок в AJAX и особенно использую его в контексте WordPress, но я следил за некоторыми онлайн-уроками, и я думаю, что я почти там.
Я вставлю то, что у меня есть, и объясню свое мышление.
Хорошо, чтобы начать, JS.
jQuery(document).ready(function(){
jQuery('.gadgets-menu').mouseenter(function(){
doAjaxRequest();
});
});
Мышь входит в .gadgets-menu, и запрос запускается при помощи mouseenter, поэтому он срабатывает один раз.
Сам запрос.
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);
}
});
}
Теперь функция 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;
}
И функция ajax_get_latest_posts
function ajax_get_latest_posts($count){
$posts = get_posts('numberposts='.'&category=20'.$count);
return $posts;
}
Итак, если я сделал это правильно, вывод должен быть$posts = get_posts('numberposts='.'&category=20'.$count);
то есть. количество постов (5) из категории 20. Я не знаю, что теперь с этим делать, как мне получить заголовок и эскиз?
Извините, если это глупо, я просто шарила здесь.
Исправленный 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;
}
Это не работает.
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...
}
}
});
}
Предупреждение не отображается.