I am testing the getJSON with php array, but it is not working, can anyone check for me ? I feel the problem is from the php code because when i test the html code with getJSON url , it is working.
In my array.php
<?php
header("Content-type: text/javascript");
$arr = array(
"name" => "Tim",
"age" => "28" );
echo json_encode($arr);
?>
In my 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>
I am testing the getJSON with php array, but it is not working, can anyone check for me ? I feel the problem is from the php code because when i test the html code with getJSON url https://graph.facebook./zombies, it is working.
In my array.php
<?php
header("Content-type: text/javascript");
$arr = array(
"name" => "Tim",
"age" => "28" );
echo json_encode($arr);
?>
In my 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>
Share
Improve this question
asked Nov 24, 2012 at 9:27
jc_tanjc_tan
551 gold badge3 silver badges9 bronze badges
2
- 1 Try the content type application/json – rekire Commented Nov 24, 2012 at 9:30
- ok i have solve my problem, in php : echo $_GET["callback"] . "(" . json_encode($arr) . ")"; in html : $.getJSON('array.php?callback=?', function(data) so the cross server can be done – jc_tan Commented Nov 24, 2012 at 10:12
3 Answers
Reset to default 3Change
header("Content-type: text/javascript");
To
header('Content-Type: application/json');
For 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. The content type for JSON is application/json
.
If you fix that, it should work, provided you're not running afoul of the Same Origin Policy. If you're making a cross-domain request, your options are:
Don't use ajax and JSON, use 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).
Use YQL as a cross-domain proxy.
Try to set the content type to
application/json
So jQuery will interpte as json data