【问题标题】:Ajax post call in admin-ajax.php returns 0 with 400 bad request (Wordpress)admin-ajax.php 中的 Ajax 发布调用返回 0 和 400 错误请求(Wordpress)
【发布时间】:2020-12-25 03:56:24
【问题描述】:

您好,您可以看到我正在尝试使用 ajax post call 将我的数据发送到 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');

【问题讨论】:

标签: wordpress


【解决方案1】:

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

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

你在这里编辑了代码

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.

【讨论】:

  • 嘿 Sohil 我已经解决了这个问题,但你仍然有权删除 ajax 中的 contentType 以及 wp_die() 是否与 die() 或 exit() 相同?
  • contentType 是你发送的数据类型,所以 application/json; charset=utf-8 是常见的,application/x-www-form-urlencoded 也是如此; charset=UTF-8,这是默认值。你可以写 die() 或 exit() 而不是 wp_die() 它会起作用。但是,如果您正在使用 wordpress ajax,那么 wp_die() 是提供的内置方法。它就像 wordpress 编写方式一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
相关资源
最近更新 更多