We all know that one of the limitations of AJAX is that it does not allow cross-domain requests. But it is achieved by using JSONP. JSONP is a way of injecting through script tags, which are js scripts that can reference cross-domain URLs, but you need to provide a callback function (must be on your own page), so you can handle the results yourself. Let's see how JSONP is implemented in jQuery, MooTools, Dojo Toolkit.
JSONP of jQuery
jQuery.getJSON method:
Js code
jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{
q: "Arsenal"
} ,function(tweets) {
// Handle response here
console.info("Twitter returned: ",tweets);
});
or similar
Js code
$.ajax({
> type: "get",
jsonp:"callback",
success:function(data){
"");
🎜>
MooTools JSONP
MooTools requires Request.JSONP Class, you can download MooTools More from here. Select Request.JSONP,
so that getting json from another domain is a piece of cake.
Js code " http://search.twitter.com/search.json",
data: {
q: "Arsenal"
},//Submitted parameters, if there are no parameters, do not write
callbackKey: 'jsoncallback',//Define the parameter name of the callback function by yourself
onComplete: function(tweets) {
// Log the result to console for inspection
console.info("Twitter returned: ",tweets) ;
}
}).send();
Copy code
The code is as follows:
String callback = request.getParameter("jsoncallback");//Get the callback method name
response.setHeader("Cache-Control", "no-cache");
response.setContentType ("text/json;charset=UTF-8");
PrintWriter out;
try {
out = response.getWriter();
out.print(callback "(" message ") "); // Here is the key. Mainly here
Out.flush ();
Out.Close ();
} Catch (IOEXception E) {
E.printstacktrace (); }
By the way: I personally like the syntax structure and framework design ideas of mootools. Praise again!
Dojo JSONP
JSONP is required in Dojo Toolkit Go to dojo.io.script (click to view the example)
Js code
// dojo.io.script is an external dependency, so it must be required
dojo.require("dojo.io.script");
// When the resource is ready
dojo.ready(function() {
// Use the get method
dojo.io.script.get({
) // The URL to get JSON from Twitter
url: "http://search.twitter.com/search.json",
// The callback paramater
callbackParamName: "callback", // Twitter requires "callback"
// The content to send
message! 🎜>
JSONP is a very effective, reliable, and easy-to-implement remote data acquisition method. The JSONP strategy also enables developers to avoid cumbersome server proxy methods and easily obtain data. You can try writing one yourself