admin-ajax.php中的Ajax帖子调用返回0,并带有400个错误的请求(Wordpress)

时间:2019-02-25 05:02:49

标签: wordpress

您好,您可以看到我正在尝试使用ajax发布调用将数据发送到admin-ajax.php,请仔细检查下面的代码,并且我使用的模板是betheme。

index.html

        $('#send-form').on('submit', function () {

            $.ajax({
                url : '<?php echo admin_url('admin-ajax.php'); ?>',
                data : {
                    'action' : 'test_func',
                    'data':'lorem ipsum'
                },
                type : 'POST',
                contentType: "application/json; charset=utf-8",
                dataType : 'json',
                success : function (callback) {

                    console.log(callback);
                }
            });

            return false;

        });

functions.php

function test_func () {
    echo json_encode(array('res'=>'return dummy text'));
}
add_action('wp_ajax_nopriv_test_func', 'test_func');

1 个答案:

答案 0 :(得分:0)

按照ajax的代码,无需添加“ contentType:” application / json; charset = utf-8”,因为您将数据作为字符串传递,因此“ contentType属性不是必需的”。要解决每次获取0的问题,只需在“ test_func”的末尾写“ wp_die()”方法。下面我提到了经过修改的代码。

1)jQuery Ajax代码:-

contentsTransform

2)functions.php代码

jQuery('#send-form').on('submit', function () {
             $.ajax({
            url : '<?php echo admin_url('admin-ajax.php'); ?>',
            data : {
                'action' : 'test_func',
                'data':'lorem ipsum'
            },
            type : 'POST',
            // contentType: "application/json; charset=utf-8",
            dataType : 'json',
            success : function (callback) {

                console.log(callback);
            }
        });

        return false;

    });
相关问题