当函数外部的echo时,Wordpress Admin ajax请求返回值为0

时间:2017-05-03 19:22:53

标签: php ajax wordpress return

$(document).ready(function () {
        //added this variable
        var stopAjaxing = false;
        $('#example').on('preXhr.dt', function (e, settings, data) {
            //changing to 100 since it works for rows, not pagges
            if (data.start + data.length >= 100) {
                //return false;
                //moved message to callback
                stopAjaxing = true;
            }
        })
        .dataTable({
            "preDrawCallback": function (settings) {
                if (stopAjaxing) {
                    alert("You need to refine  your search");
                    return false;
                }
                else {
                    return true;
                }
            },  
...

它返回值为0.如何修复它。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用以下代码片段从数据库中获取fetech数据并使用json_encode()对其进行编码,然后调用wp_die()

add_action('wp_ajax_ybr_client_results', 'ybr_client_results');
add_action( 'wp_ajax_nopriv_ybr_client_results', 'ybr_client_results' );

function ybr_client_results() {

   $client_details = $_POST[ 'client_details' ];

   $result = getPosts();

   echo json_encode($result, true);

    wp_die();
}

答案 1 :(得分:0)

您已正确注册了AJAX回调;代码将在触发AJAX操作时执行。该功能不应该回应。

回调本身存在一些问题:

  • 它返回一个变量而不是生成输出
  • die()之上有一个返回语句,因此永远不会到达

更正版本:

function ybr_client_results() {
    /**
     * I've left this unaltered for the sake of answering the question at hand.
     *
     * Don't forget to check the value exists and sanitize it correctly.
     */
    $client_details = $_POST['client_details'];

    // This AJAX callback needs to output something, not return.
    echo $client_details;

    // As another user mentioned, there's a WP specific die function.
    wp_die();
}
add_action( 'wp_ajax_ybr_client_results', 'ybr_client_results' );
add_action( 'wp_ajax_nopriv_ybr_client_results', 'ybr_client_results' );

文档:https://codex.wordpress.org/AJAX_in_Plugins