我正在尝试向API发出POST请求。我已经在主题中创建了一个javascript文件,到目前为止,我已经尝试了两种方法:
方法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(跨原始资源共享)而阻止任何调用
方法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' );
我在主题的header.php文件中声明了一个ajaxUrl
变量:
<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
文件中正确设置了我的JavaScript文件:
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端点时寻求帮助。