[英]Jquery getJSON php array to javascript
I am testing the getJSON with php array, but it is not working, can anyone check for me ? 我正在用php数组测试getJSON,但是它不起作用,有人可以帮我检查一下吗? I feel the problem is from the php code because when i test the html code with getJSON url https://graph.facebook.com/zombies , it is working. 我觉得问题出在php代码,因为当我使用getJSON url https://graph.facebook.com/zombies测试html代码时,它正在工作。
In my array.php 在我的array.php中
<?php
header("Content-type: text/javascript");
$arr = array(
"name" => "Tim",
"age" => "28" );
echo json_encode($arr);
?>
In my test.html : 在我的test.html中:
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
</head>
<body>
<script type='text/javascript'>
$(document).ready(function() {
$.getJSON('array.php', function(data) {
if(data) {
document.write(data.age);
}
else {
alert('error');
}
});
});
</script>
</body>
</html>
Change 更改
header("Content-type: text/javascript");
To 至
header('Content-Type: application/json');
For JSONP 对于JSONP
header('Content-Type: application/javascript');
header("Content-type: text/javascript");
You're telling the browser you're sending it JavaScript, when what you're sending it is JSON. 您告诉浏览器要发送的是JavaScript,而发送的是JSON。 The content type for JSON is application/json
. JSON的内容类型为application/json
。
If you fix that, it should work, provided you're not running afoul of the Same Origin Policy . 如果您对此进行了修复,只要您不违反Same Origin Policy ,它就可以正常工作。 If you're making a cross-domain request, your options are: 如果您要进行跨域请求,则可以选择:
Don't use ajax and JSON, use JSON-P . 不要使用ajax和JSON,请使用JSON-P 。
Use CORS , but it requires that the server allow your document's origin, and that the browser supports it (most modern ones do, older ones don't). 使用CORS ,但是它要求服务器允许您文档的原始来源,并且浏览器支持它(大多数现代浏览器都支持,较旧的浏览器不支持)。
Use YQL as a cross-domain proxy . 使用YQL作为跨域代理 。
Try to set the content type to 尝试将内容类型设置为
application/json
So jQuery will interpte as json data 因此,jQuery将作为json数据插入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.