我有一个返回JSON的url,但由于跨浏览器请求问题,我用PHP中的CURL请求它,现在它以字符串形式返回JSON数据。我想把这个字符串转换成json,这样我就可以把它和我的javascript函数一起使用了。
正在打印JSON字符串的Ajax请求
$.ajax({
url: 'tweet.php',
cache: false,
dataType: 'json',
type: 'POST',
data: {
url : url,
},
success: function(tweet){
var tweets = $.parseJSON(tweet);
console.log(tweets);
}
});
和在tweet.php
header('Content-type: application/json');
$ch = curl_init() or die('cURL not available');
curl_setopt($ch, CURLOPT_URL, $_POST["url"]. $location);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);
print ($result);
获取无效json错误
已解决
虽然答案没有帮助,但不知怎么的,我明白了。如果有人需要,请在这里张贴。
每当您使用Curl从PHP请求JSON时,它都会返回JSON对象,但作为字符串,您可以通过javascript typeof()函数进行检查。如果要将该字符串转换为真正的javascript对象,则需要使用某种解析器。这是我用的JSON解析器
var myJson = '{ "x": "Hello, World!", "y": [1, 2, 3] }';
var myJsonObj = jsonParse(myJson);
console.log(myJsonObj);
问候
在您的html文件中,假设$json
包含从远程url 返回的json字符串
<script type="text/javascript">
var data = JSON.parse("<?php echo $json; ?>");
</script>
尝试jQuery.parseJSON
另外,如果您希望您的php响应被视为json内容,请在php中使用以下模式:
// Convert to JSON
$json = json_encode($yourData);
// Set content type
header('Content-type: application/json');
// Prevent caching
header('Expires: 0');
// Send Response
print($json);
exit;
在$.ajax调用