我有这个 JSON 数据:
$.ajax({
type: "GET",
url: "http://www.example.com/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
});
要将此数据发送到http://www.example.com/test.php
,我尝试使用以下代码:
<?php
//API URL
$url = 'http://www.example.com/test.php';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'data' => 'code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
?>
但是,它总是返回无法访问
。
我的代码有什么问题?你能帮我解决这个问题吗?
<小时/>Sorry about my English, it is not good. If my my question is not clear, please comment below this question.
最佳答案
首先检查http://www.example.com/test.php
Ajax系统不能使用完整域名。
所以你应该使用/test.php
然后检查您的网站或目标网站中是否出现错误。
那么代码就变成了:
$.ajax({
type: "GET",
url: "/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
success: function(data, textStatus) {
alert(data);
data = $.parseJSON(data);
},
error : function(data, textStatus, error){
alert(data + " : "+ textStatus);
}
});
关于php - 通过 cURL 发送 JSON 始终返回 "No access",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31737205/