为什么我的 ajax 请求得到响应 0


Why is my ajax request getting response 0?

我已经在我的wp主题中设置了基本的wordpress ajax示例。触发器由 modernizr .js检查页面上的媒体查询

jQuery(document).ready(function($) {
    if(Modernizr.mq('only all and (max-width:6300px)')) {
        var data = {
        action: 'my_action',
        whatever: ajax_object.we_value      // We pass php values differently!
    };
    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
        jQuery.post(ajax_object.ajax_url, data, function(data) {
            $("#trending-Container").html(data).fadeIn(1000);
        });
    }
});//end function 

我已经本地化并排队我的脚本。

wp_enqueue_script('mainJS', get_template_directory_uri() . '/js/mainJS.js', array("jquery") );
wp_localize_script( 'mainJS', 'ajax_object', 
                    array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );

最后,处理请求的函数是:

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {
        global $wpdb;
            $whatever = intval( $_POST['whatever'] );
            $whatever += 10;
                echo $whatever;
            die();
        }

这不断给我一个 0(没有属性)的响应,我不知道为什么。附言这都是本地的。

Status code 200
Host:lart.co.uk
Origin:http://lart.co.uk
Referer:http://lart.co.uk/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
action:my_action
whatever:1234

一切都必须在这里匹配:

.PHP

add_action("wp_ajax_my_action"、"my_action");add_action("wp_ajax_nopriv_my_action"、"my_action");函数 my_action() {}

.JS

变量数据 = {    操作:"my_action",    无论什么: ajax_object.we_value};

此外,您还缺少安全检查和更好地处理响应。
检查以下示例:[ 1 ][ 2 ]。

添加函数的"exit"结尾,如下所示,这将修复返回 0 与 WordPress 中使用 ajax 请求的响应。

add_action('wp_ajax_nopriv_getStateList', 'getStateList');
add_action('wp_ajax_getStateList', 'getStateList');
function getStateList() {
    global $wpdb;
    $countryId = $_POST['countryId'];
    $results = $wpdb->get_results("SELECT id,name FROM regions where country_id ='".$countryId."' ");
    echo json_encode(array('status'=>200,'data'=>$results));
    exit;
}

以下是解决此问题的完整示例:

JavaScript:

$(document).ready(function() {
    $("#submit").click(function(e) {
        var demo = 'demo';
        var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
        data = { action: "data_insert", demo: demo};     
        $.ajax({
            url: ajaxurl,
            data: data,
            dataType: 'json',
            type: 'post',
            success: function(response) {
              console.log(response);  
            }
        });
    });    
});

.PHP:

add_action('wp_ajax_data_insert', 'data_insert');
add_action('wp_ajax_nopriv_data_insert', 'data_insert');
function data_insert() {
    $data = $_POST['demo'];
    echo json_encode($data);
    die();
}