【发布时间】:2017-11-23 15:59:52
【问题描述】:
我已经设置了一个代理,它允许我从只有 api 可访问的服务器端检索数据用户端。我有几个端点设置,它们都工作得很好,但现在我需要将数据发送回 api 进行预订。我需要
- 从代理中的 ajax 请求中检索数据
- 将代理中的数据发送到 api
- 从 api 向 ajax 请求返回成功/错误消息
我不知道该怎么做。这是我的 ajax 请求:
var settings2 = {
"async": true,
"crossDomain": true,
"url": "http://url?method=hello&format=json&entity=" + id,
"dataType": "json",
"data": data,
"method": "POST"
};
var a2 = $.ajax(settings2);
$.when(a2).done(function(d2) {
rp = d2;
console.log(JSON.stringify(rp));
});
以及我用于只需要从 api 检索数据的其他端点的 php 函数和方法,它适用于此:
function LocationReserve(data) {
header('Content-Type: application/json');
$url = 'api_url' . $_GET['entity'] ;
$auth = 'Authorization: key';
$ch = curl_init($url);
$options = array(
CURLOPT_HTTPHEADER => array(
$auth
),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION, 1
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Method A: Say Hello to the API
if( strcasecmp($_GET['method'],'hello') == 0){
$response['code'] = 1;
$response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
$response['data'] = wssLocationReserve();
}
// --- Step 4: Deliver Response
// Return Response to browser
deliver_response($_GET['format'], $response);
就这样我得到了回复
{"code":1,"status":200,"data":"{\"Message\":\"The requested resource does not support http method 'GET'.\"}"}
我将 CURLOPT_POST => true 添加到我的选项中,现在响应是
{"code":1,"status":200,"data":"<html><head><title>411 Invalid Request</title></head><body>Invalid Request: ??</body>\r\n"}
如何修改它以接受来自我的 ajax 调用的数据,将其发送到 api_url,然后发回响应?
**通过 api 编辑示例预期数据:
{
"ReservationDay": "05/15/2015",
"Units": [{
"UnitID": 12345,
"InsuranceID": 123 (or null)
}],
"PaymentInfo": {
"FirstName": "User",
"LastName": "Userson",
"Address1": "2727 N Central Ave",
"Address2": "",
"City": "Phoenix",
"State": "AZ",
"Zip": "85022",
"Phone": "602-2877878",
"Email": "email@example.com",
"CreditCard": "6011000000000000",
"ExpirationMMYY": "1215",
"CSC": "100"
}
}
【问题讨论】:
-
听起来您正在寻找 POST 而不是 GET。使用 cURL,您需要
curl_setopt($ch, CURLOPT_POST, 1);。 -
我在选项中添加了 CURLOPT_POST => true ,现在响应为 {"code":1,"status":200,"data":"
411无效请求 无效请求:??\r\n"}