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

    q: "Arsenal" 
},function(tweets) { 
    // Handle response here"Twitter returned: ",tweets); 

Or similar

Js code

                      $.each(data, function(key, val) { 

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: "", 
    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"Twitter returned: ",tweets); 

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"); 
        PrintWriter out; 
        try { 
            out = response.getWriter(); 
            out.print(callback+"("+message+")");//Here's the key. Here's the main thing
        } catch (IOException e) { 

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

Dojo json
JSONP requires the use of in the Dojo Toolkit (click to see an example)

Js code

// is an external dependency, so it must be required 

// When the resource is ready 
dojo.ready(function() { 

    // Use the get method{ 
        // The URL to get JSON from Twitter 
        url: "", 
        // 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 
  "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: