JQUERY JSONP issue
I am using Jquery 1.6.2.
This works:
$.getJSON("http://b.webvm.net/?jsoncallback=?",
function(data) {
alert("OK");
});
});
but this does not:
$.getJSON("http://isp123开发者_运维问答.co.uk/cw/NorthWales/test.txt?jsoncallback=?",
function(data){
alert("OK");
});
});
Both remote files look identical:
http://b.webvm.net/?jsoncallback=?
and
http://isp123.co.uk/cw/NorthWales/test.txt?jsoncallback=?
however the alert message never gets fired on the second example.
The text file doesn't provide a callback function like the other link does. jQuery isn't actually calling http://b.webvm.net/?jsoncallback=? but instead something like http://b.webvm.net/?jsoncallback=jQuery2239203480932480392849032809 which then in turn calls that function within your script:
jQuery2239203480932480392849032809({"name" : "hello world"});
The textfile on the other hand, doesn't call any function even when jQuery adds the callback function http://isp123.co.uk/cw/NorthWales/test.txt?jsoncallback=jQuery2239203480932480392849032809 returns
({"name" : "hello world"});
To solve this, you can use the jsonpCallback
parameter in your ajax request to force jQuery to use a static function, which you would then wrap your json in.
For example if you set jsonpCallback
to "mycallback", then your text file should return:
mycallback({"name" : "hello world"});
I notice that the first example is being returned with the mime type "text/html" and the second is being returned with "text/plain". Your browser may not interpret the "text/plain" mime type correctly. Try returning the second one back as text/html or application/json
精彩评论