首页 > 解决方案 > admin-ajax.php 中的 Ajax 发布调用返回 0 和 400 错误请求(Wordpress)

问题描述

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

索引.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;

        });

函数.php

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

标签: wordpress

解决方案


根据 ajax 的代码不需要添加contentType: "application/json; charset=utf-8,因为您将数据作为字符串传递,所以contentType不需要属性。

要解决0每次获取的问题,您只需在方法wp_die()末尾添加即可test_func

在这里你编辑了代码

1) jQuery Ajax 代码:

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;

    });

2) 代码functions.php

function test_func () {
    echo json_encode(array('res'=>'return dummy text'));
    wp_die();
}
add_action('wp_ajax_nopriv_test_func', 'test_func'); // ajax call for non-login user.
add_action('wp_ajax_test_func', 'test_func'); // ajax call for login user.

推荐阅读