函数文件中提交函数的AJAX错误处理

时间:2019-05-15 作者:user13286

我在中创建了一个自定义函数functions.php 处理Mailchimp订阅服务器列表的表单提交。我正在JavaScript中调用AJAX来处理PHP。我面临的问题是,即使Mailchimp函数不成功,我的AJAX调用也总是返回“success”。当Mailchimp subscribe函数成功时,它将返回代码200, 如果不成功,将返回代码400. 如何重新配置JS,使代码400 会在AJAX调用中触发错误函数吗?

下面是我的PHP函数的一部分:

curl_setopt($mchAPI, CURLOPT_URL, \'https://\' . substr($apiKey, strpos($apiKey, \'-\') + 1) . \'.api.mailchimp.com/3.0/lists/\' . $listID . \'/members/\' . md5(strtolower($email)));
curl_setopt($mchAPI, CURLOPT_HTTPHEADER, array(\'Content-Type: application/json\', \'Authorization: Basic \' . base64_encode(\'user:\' . $apiKey)));
curl_setopt($mchAPI, CURLOPT_USERAGENT, \'PHP-MCAPI/2.0\');
curl_setopt($mchAPI, CURLOPT_RETURNTRANSFER, true);
curl_setopt($mchAPI, CURLOPT_CUSTOMREQUEST, \'PUT\');
curl_setopt($mchAPI, CURLOPT_TIMEOUT, 10);
curl_setopt($mchAPI, CURLOPT_POST, true);
curl_setopt($mchAPI, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($mchAPI, CURLOPT_POSTFIELDS, json_encode($data));

$result = curl_exec($mchAPI);
$responseCode = curl_getinfo($mchAPI, CURLINFO_HTTP_CODE); // This will return \'200\' if successful or \'400\' if unsuccessful
以下是我的AJAX调用:

$.ajax({
    url: postURL, 
    method: \'POST\',
    data: serialized,
    success: function(response) {
        // Always ends here even if subscribe is unsuccesful
        alert(\'SUCCESS!\');
    },
    error: function(xhr, ajaxOptions, thrownerror) {
        alert(\'FAILED \' + thrownerror);
    }
});

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

如何重新配置JS,使代码400 会在AJAX调用中触发错误函数吗?

这个error 在您的$.ajax() 如果服务器响应的HTTP状态标头不是“OK”(代码:200),因此通过处理AJAX请求的PHP函数,只需发送一个HTTP状态头和代码400 (“错误请求”)当$responseCode400.

您可以使用wp_die():

add_action( \'wp_ajax_your-action\', function(){
    ...
    $responseCode = curl_getinfo($mchAPI, CURLINFO_HTTP_CODE);

    // Send a response and the HTTP status header.
    if ( \'200\' == $responseCode ) {
        echo \'Subscribed\'; // success message/data

        wp_die(); // here the code defaults to 200
    } else {
        echo \'Not subscribed\'; // error message/data

        wp_die( \'\', 400 );
    }
} );
或使用status_header() 发送自定义HTTP错误消息;i、 e.违约除外Bad Request 当代码为400:

add_action( \'wp_ajax_your-action\', function(){
    ...
    $responseCode = curl_getinfo($mchAPI, CURLINFO_HTTP_CODE);

    // Send a response and the HTTP status header.
    if ( \'200\' == $responseCode ) {
        echo \'Subscribed\'; // success message/data

        status_header( 200, \'OK\' );
    } else {
        echo \'Not subscribed\'; // error message/data

        status_header( 400, \'Custom HTTP Error\' );
    }

    die(); // not wp_die()
} );