I use the following jQuery to fetch some JSON from a x-server:
$(function(){
$.getJSON("/json.php?method=getStupid&jsoncallback=?",
function(json){
console.log('Success: ' + json);
}
);
});
The console is empty in every browser, but when I check the networks tab it all seem to work perfectly fine.
HTTP/1.1 200 OK
Date: Mon, 04 Feb 2013 14:14:01 GMT
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7+squeeze9
Cache-Control: no-cache, must-revalidate
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Content-Length: 33
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: application/json
And this is what the response looks like:
({"a":1,"b":2,"c":3,"d":4,"e":5})
It feels like everything within the function(json) { } is getting ignored. Is it a typo?
You are appending
jsoncallback=?, which means you are requesting JSONP. This is only used for cross-domain communication. If this URL is on your domain, then just use JSON.Lose the
jsoncallback=?, and the()around the JSON in the response. Then it will be valid JSON.If you need to use JSONP, you need to format the request correctly.
First, JSONP is not JSON. It’s actually a script tag being appended to the page. So, its
Content-typeshould betext/javascript.Second, the
jsoncallbackparameter is important. When sending back a response, you need to “wrap” the data in the value of that param.So, if the request was
/json.php?method=getStupid&jsoncallback=test123, the response should be: