我正在尝试向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端点时获得帮助。