在WordPress中实现AJAX POST API调用

时间:2019-01-26 作者:suo

我正在尝试向API发出POST请求。我已经在我的主题中创建了一个javascript文件,到目前为止,我已经尝试了两种方法:

Approach 1:

$.ajax({
        headers:{  
            "Content-Type":"application/json"               
        },   
        data:{
            "command": "request",
            "data": {
                "api_key": "my_api_key",
                "api_username": "my_api_username",
                "vendor_type": 2,
                "from": {
                  "from_name": "",
                  "from_lat": "",
                  "from_long": "",
                  "from_description": ""
                },
                "to": {
                  "to_name": customerLocation,
                  "to_lat": cityLat,
                  "to_long": cityLng,
                  "to_description": ""
                },
                "recepient": {
                    "recepient_name": name,
                    "recepient_phone": phone,
                    "recepient_email": email,
                    "recepient_notes": ""
                },
                "delivery_details": {
                  "pick_up_date": pickupdate,
                  "collect_payment": {
                    "status": false,
                    "pay_method": 0,
                    "amount": amountTotal
                  },
                                      "return": true,
             "note": " Sample note",
              "note_status": true,
              "request_type": "quote"
            }
            },
            "request_token_id": requestToken
            },
        type: \'POST\',
        url:"https://apitest.sendyit.com/v1/",
        success: function(response){
           console.log(\'success\');
           console.log(response);
        },
        error: function(response){
            console.log(\'error\');
            console.log(response);
        }
    });
上面的代码不会从API返回响应负载,因为任何调用都会因为CORS(跨源资源共享)而被阻止

Approach 2

然后,我尝试将端点传递给functions.php 文件如下:

//make api call to sendy
function foo() 
{
     echo \'https://apitest.sendyit.com/v1/\';
}
add_action(\'wp_ajax_foo\', \'foo\' );
add_action(\'wp_ajax_nopriv_foo\', \'foo\' );
我声明ajaxUrl 我的主题标题中的变量。php文件:

<script type="text/javascript">
var ajaxUrl = "<?php echo admin_url(\'admin-ajax.php\'); ?>";
</script>
然后格式化我的Ajax调用,如下所示:

$.ajax({
        headers:{  
            "Content-Type":"application/json"               
        },   
        data:{
            "action": \'foo\',
            "command": "request",
            "data": {
                "api_key": "my_api_key",
                "api_username": "my_api_username",
                "vendor_type": 2,
                "from": {
                  "from_name": "",
                  "from_lat": "",
                  "from_long": "",
                  "from_description": ""
                },
                "to": {
                  "to_name": customerLocation,
                  "to_lat": cityLat,
                  "to_long": cityLng,
                  "to_description": ""
                },
                "recepient": {
                    "recepient_name": name,
                    "recepient_phone": phone,
                    "recepient_email": email,
                    "recepient_notes": ""
                },
                "delivery_details": {
                  "pick_up_date": pickupdate,
                  "collect_payment": {
                    "status": false,
                    "pay_method": 0,
                    "amount": amountTotal
                  },
                                      "return": true,
             "note": " Sample note",
              "note_status": true,
              "request_type": "quote"
            }
            },
            "request_token_id": requestToken
            },
        type: \'POST\',
        url:ajaxurl,
        success: function(response){
           console.log(\'success\');
           console.log(response);
        },
        error: function(response){
            console.log(\'error\');
            console.log(response);
        }
    });
但这给了我一个400 (Bad Request) 错误

我应该提到,我已经在functions.php 文件:

wp_enqueue_script(\'sendy\', get_template_directory_uri() . \'/assets/js/sendy.js\', array(\'jquery\'));
wp_localize_script(\'sendy\', \'wc_checkout_params\', array(\'ajaxurl\' => admin_url(\'admin-ajax.php\')));
因此,希望在设置我的POST端点时获得帮助。

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

你搞错了400 Bad Request 因为Content-Type 标题为application/json:

$.ajax({
  headers:{
    "Content-Type":"application/json"
  },
  data: {
    ...
  },
  ...
});
当请求内容是JSON字符串时$_REQUEST[\'action\'] WordPress使用哪个词来识别正确的AJAX操作(即foo 在您的代码中)不可用(即NULL).

因此,根据您的代码,使用第二种方法,您可以省略headers 部分

$.ajax({
  // No "headers" here.
  data: {
    ...
  },
  ...
});
更新您可以使用wp_remote_post() 从发出外部API请求foo() 功能示例:

function foo() {
    if ( empty( $_POST[\'data\'] ) ) {
        wp_die( \'Missing data\' );
    }

    $post_data = wp_unslash( $_POST[\'data\'] );
    $post_data[\'command\'] = wp_unslash( $_POST[\'command\'] );
    $post_data[\'request_token_id\'] = wp_unslash( $_POST[\'request_token_id\'] );

    $api_url = \'https://apitest.sendyit.com/v1/\';
    $response = wp_remote_post( $api_url, array(
        // Set the Content-Type header.
        \'headers\' => array(
            \'Content-Type\' => \'application/json\',
        ),
        // Set the request payload/body.
        \'body\'    => json_encode( $post_data ),
    ) );

    $res_body = wp_remote_retrieve_body( $response );
    echo $res_body;

    wp_die();
}