Wordpress Ajax调用成功(200),但没有响应消息

时间:2019-04-25 06:57:53

标签: php jquery ajax wordpress

我正在使用Wordpress,将AJAX请求从网站上的表单发送到服务器,但是即使状态为200,也看不到响应消息。

页脚中的JS

var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
var data = [somedata]

fetch(ajaxurl, {
    method: 'POST',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    dataType:'json',
    credentials: 'include',
    body: 'action=process_request&data='+data
}).then(function (result) {
    console.log(result);
});

PHP

add_action('wp_ajax_process_request', 'process_request');
add_action('wp_ajax_nopriv_process_request', 'process_request');

function process_request() {

    header("Content-type: application/json");
    //do something with data
    echo json_decode('my_response');
    die();
}

服务器的响应

Response {type: "basic", url: "https://myserver.xyz/wp-admin/admin-ajax.php", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "https://myserver.xyz/wp-admin/admin-ajax.php"
__proto__: Response

1 个答案:

答案 0 :(得分:0)

您在 response.body 中具有响应正文。现在,您已获得有关响应的所有信息。

var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
var data = [somedata]

fetch(ajaxurl, {
    method: 'POST',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    dataType:'json',
    credentials: 'include',
    body: 'action=process_request&data='+data
}).then(result => result.json())
  .then(function (result) {
    console.log(result);
});

和发送响应功能:

add_action('wp_ajax_process_request', 'process_request');
add_action('wp_ajax_nopriv_process_request', 'process_request');

function process_request() {
    //do something with data
    echo json_decode('{"a":1,"b":2,"c":3,"d":4,"e":5}', true);

    wp_die();
}

您不能在此位置设置标题,这是行不通的。 WordPress有一个特殊的钩子。

在您的情况下:

add_action( 'send_headers', 'addHeader' );
function addHeader() {
    header("Content-type: application/json");
}

以前,我忘记了将值转换为JSON,所以我编辑了答案!

问候,李子!

来源:

WordPress标头挂钩:https://codex.wordpress.org/Plugin_API/Action_Reference/send_headers

获取API:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

获取响应文档:https://developer.mozilla.org/en-US/docs/Web/API/Response