我正在使用自己创建的API(正在与我进行通信),并使用下面的代码。如果一切正常,API将返回json以及 header “200 OK”。但是,如果连接断开,则返回“502 Bad Gateway”作为标题。
到目前为止,“CURLOPT_HEADER”已在我的php脚本中设置为false(下面的se),但是现在我将其设置为true,以便我可以接收 header 并根据 header 采取措施。在这里我需要帮助。
实际上,我有两件事需要帮助(它们相互关联):
所以,请在这里帮助我。提前致谢!
PHP:
$url = 'http://theurl.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
if(!$response) {
// <--- ??
}
curl_close($ch);
echo json_encode($response);
JS:
1. $.ajax({
2. url:'./php/apihandling.php',
3. type:'post',
4. dataType:'json',
5. data:{
6. data: data
7. },
8. success: function(data) {
9. var content = JSON.parse(data);
10. console.log(content);
11. },
12. error: function (xhr, ajaxOptions, thrownError) {
13. console.log(xhr.status);
14. console.log(thrownError);
15. }
16. });
最佳答案
您可以使用curl_errno检查您的API如何响应您的请求,也可以尝试使用API“状态标志”以避免JQuery中的错误
...
// Check if any error occurred
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
//close the connection
curl_close($ch);
$result["API_status"]=0;
$result["error"]=$info;
//kill the script and echo the json
die(json_encode($result));
}
else
{
$result["API_status"]=1;
curl_close($ch);
$result["response"]=$response;
echo json_encode($result);
}
现在让我们尝试一下您的jquery脚本
$.ajax({
url: './php/apihandling.php',
type: 'post',
dataType: 'json',
data: {
data: data
},
success: function(data) {
//no need for this, datatype is json already
//var content = JSON.parse(data);
if (data["API_status"]) {
alert("wow API is up and healthy");
//do some stuff with the json
$.each(data["response"], function(index, value) {
//loop this
});
} else {
alert("Oh, no. RIP API");
console.log(data["error"]);
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
关于php - 接收和处理无连接错误和200 OK header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14957052/