An implementation of AJAX to request json data across domains

  • 2020-03-27 00:01:43
  • OfStack

As we all know, a big limitation of AJAX is that it doesn't allow cross-domain requests. But by using JSONP. JSONP is a way of injecting by script tag, which is a js script that can reference cross-domain urls, but needs to provide a callback function (it must be on your own page), so you can handle the result yourself. Let's see how JSONP is implemented in jQuery, MooTools, and the Dojo Toolkit.

JQuery json
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", 
                data:"random="+Math.random(), 
                url:url, 
                dataType:"jsonp", 
                jsonp:"callback", 
                success:function(data){ 
                      $.each(data, function(key, val) { 
                        $("#myDiv").html($("#myDiv").html()+val.cvalue+"</br>"); 
                      }); 
                } 
            }); 

The parameters of the callback method are retrieved from the json object by getJSON

MooTools json
MooTools requires requeste.jsonp Class, which you can download from here. Select the Request. The json,
Getting json from another domain is a piece of cake.

Js code

new Request.JSONP({ 
    url: "http://search.twitter.com/search.json", 
    data: { 
        q: "Arsenal" 
    },//Submitted parameters, no parameters can not write
        callbackKey: 'jsoncallback',//Define the parameter name of the callback function
        onComplete: function(tweets) { 
        // Log the result to console for inspection 
        console.info("Twitter returned: ",tweets); 
    } 
}).send(); 

If you define the parameter name of the callback function, just like jquery.

On the server side you need to get:

Js code

String callback = request.getParameter("jsoncallback");//Gets 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's the key. Here's the main thing
            out.flush(); 
            out.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 

By the way, I prefer the syntax structure and framework design ideas of mootools.

Dojo json
JSONP requires the use of dojo.io.script in the Dojo Toolkit (click to see an 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 
        content: { 
            q: "Arsenal" 
        }, 
        // The success callback 
        load: function(tweetsJson) {  // Twitter sent us information! 
            // Log the result to console for inspection 
            console.info("Twitter returned: ",tweetsJson); 
        } 
    }); 
}); 

JSONP is a very efficient, reliable, and easy to implement remote data acquisition. JSONP's strategy also enables developers to avoid cumbersome server proxy methods and easily access data. You can write one yourself

Related articles: