【问题标题】:Returning JSON data with ajax in wordpress在wordpress中使用ajax返回JSON数据
【发布时间】:2013-08-01 08:15:53
【问题描述】:

好的,这是一个相当长的问题。我对 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); 即。第 20 类的员额数 (5)。 我现在不知道该怎么办,我如何获得标题和缩略图?

如果这很愚蠢,我很抱歉,我只是在这里摸索。

修改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...
            }
        }


     });

} 

不显示警报。

【问题讨论】:

  • 您是否检查了 Chrome 开发工具上的网络选项卡以检查响应状态和文本?你也确定ajax调用的url是正确的吗?您是不是缺少文件夹/站点的名称,还是在本地主机上处理 htdocs 的根目录?

标签: ajax json wordpress


【解决方案1】:

在您的代码中 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;
}

然后在你的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!'));
    }

在你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...
    }
}

您可以阅读here 关于wp_send_json_error 辅助函数以了解有关辅助函数的更多信息。

更新:

还要记住,在$output=json_encode($output); 之后,$output 不再是一个数组,而是一个json 字符串,所以is_array($output) 将返回false,但如果您在使用is_array() 对其进行编码之前使用它$output=json_encode($output);点赞

if( is_array( $output ) ) {
    $output = json_encode( $output );
}

在这种情况下,is_array( $output ) 将返回 true

An example/simulation.

【讨论】:

  • 以及如何用JS在页面上实际输出?
  • 你必须loopresultappend页面中的每一行/一些字段。
  • 原谅我,Sheikh,但我不知道如何用 JS 做到这一点!这实际上是我的问题。
  • 如果你得到posts,那么data.results(根据我的回答)将包含所有帖子作为Javascript对象的数组,你可以使用$.eachcheck this answer)循环或for().
  • 是的,谢赫,我可能会这样做,但我真的很感谢你的努力,你是冠军。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2015-04-30
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 2017-10-22
相关资源
最近更新 更多