Ajax Jquery - 数据类型JSON始终响应null

时间:2015-04-14 10:56:00

标签: javascript jquery ajax wordpress

我想创建一个简单的jQuery Ajax代码,以便在有人点击" Check Discount Code"按钮。我创建了这个原型:

<script>
jQuery(function($) {

    $("#btn-check-discount").click(function() {
        checkdiscountcode();
    });

    // end document ready

    function checkdiscountcode() {
        var discountValue = $("#discount_code").val();
        var nonce = "<?php echo wp_create_nonce("
        getdiscount_nonce "); ?>";
        alert(discountValue);
        alert(nonce);
        $.ajax({
            type: "post",
            dataType: "json",
            url: "<?php echo admin_url() . "
            admin - ajax.php " ?>",
            data: {
                action: "getdiscount",
                discountValue: discountValue
            },
            success: function(response) {
                alert(response);
                if (response.message == "found") {
                    alert("Code Correct");
                } else {
                    alert("Code InCorrect!!! Please Try it Again");
                }
            }
        });
    }
});
</script>

的functions.php:

add_action("wp_ajax_getdiscount", "getdiscount");
add_action("wp_ajax_nopriv_getdiscount", "getdiscount");

function getdiscount() {

    $return = array(
            'message'   => 'Found',
            'ID'        => 1
    );
    wp_send_json($return);
}

此代码无效。我已经添加了一些警告(响应),希望我会从警报中得到Array()响应,但它会一直给我&#34; Null&#34;。 谁能帮助我找到罪魁祸首?我在WordPress 3.9.3中实现了这段代码。

1 个答案:

答案 0 :(得分:0)

修改您的add_action挂钩,如下所示,并尝试一下:

add_action("wp_ajax_getdiscount", "getdiscount");
add_action("wp_ajax_nopriv_getdiscount", "getdiscount"); // remove '2' from wp_ajax_nopriv_getdiscount

而不是

add_action("wp_ajax_getdiscount", "getdiscount");
add_action("wp_ajax_nopriv_getdiscount2", "getdiscount");