ajax implements JSONP across domains

Posted by mband2000 on Sat, 29 Jun 2019 01:09:42 +0200

A major limitation of AJAX is that cross-domain requests are not allowed. But by using JSONP. JSONP is a script tag injection method. It can refer to js scripts of cross-domain URL s, but it needs to provide a callback function (which must be on your own page), so you can handle the results yourself.

What is cross-domain

Simply put, for security reasons, JavaScript in the page cannot access data on other servers, namely "homology policy". Cross-domain is to achieve the effect of communication between different servers by some means to circumvent the limitation of homology policy.

Specific policy constraints can be seen in the following table:

URL Explain Allow communication
http://www.a.com/a.js
http://www.a.com/b.js
Under the same domain name allow
http://www.a.com/lab/a.js
http://www.a.com/script/b.js
Different folders under the same domain name allow
http://www.a.com:8000/a.js
http://www.a.com/b.js
Same domain name, different ports Not allow
http://www.a.com/a.js
https://www.a.com/b.js
Same domain name, different protocols Not allow
http://www.a.com/a.js
http://127.0.0.100/b.js
Domain name and domain name correspond to ip Not allow
http://www.a.com/a.js
http://script.a.com/b.js
The main domains are the same, but the subdomains are different. Not allow
http://www.a.com/a.js
http://a.com/b.js
Different secondary domain names under the same domain name Not allow
http://www.a.com/a.js
http://www.b.com/b.js
Different domain names Not allow

What is JSONP?

JSON(JavaScript Object Notation) is a lightweight data exchange format, while JSONP (JSON with Padding) is a "usage mode" of JSON, through which cross-domain data acquisition can be achieved.

Application of JSONP

JSONP can play a very important role in open API. Open API is used in developers'own applications, and many applications are often on developers' servers. Therefore, cross-domain requests for data become a major problem that developers need to solve. The majority of open platforms should support JSONP, which Sina Weibo Open Platform has done very well (although a certain one). Some APIs are not described, but they can actually be invoked using JSONP.

Principle of JSONP Cross-Domain

Under the same source strategy, the page under a server can not get data outside the server, but img, iframe, script and other tags are an exception, these tags can request data to other servers through src attributes. Using the open strategy of script tags, we can request data across domains, of course, also need the cooperation of the server. When we normally request a JSON data, the server returns a string of JSON-type data, and when we use JSONP mode to request data, the server returns an executable piece of JavaScript code.

For example, if you need to slave the server( The data obtained at http://www.a.com/user?id=123 are as follows:

{id": 123,"name": Zhang San,"age": 17} 

Then, request in JSONP mode( http://www.a.com/user?id=123?callback=foo) data will be as follows:

foo({"id": 123, "name": Zhang San, "age": 17});

Of course, if the server considers it more fully, the data returned may be as follows:

try{foo({"id": 123, "name" : Zhang San, "age": 17});}catch(e){}

At this point, we just need to define a foo() function and dynamically create a script tag with the src attribute of http://www.a.com/user?id=123?callback=foo

function executeJsonp(url){
  var eleScript= document.createElement("script");
  eleScript.type = "text/javascript";
  eleScript.src = url;
  document.getElementsByTagName("head")[0].appendChild(eleScript);
}
function foo(data){
    for(var p in data){
      console.log(data[p]);
    }
}
var url = "http://www.a.com/user?id=123?callback=foo";
executeJsonp(url)

How to get data across domains through JSONP in jQuery

The first method is to set dataType to'jsonp'in the ajax function:


$.ajax({ 
    type:"get", 
         data:"random="+Math.random(), 
         url:url, 
         dataType:"jsonp", 
         jsonp:"callback", 
         success:function(data){ //Processing data data
         $.each(data, function(key, val) { 
            $("#myDiv").html($("#myDiv").html()+val.cvalue+"</br>"); 
         }); 
        } 
}); 

The second method is to use getJSON to implement, as long as the callback=? Parameter is added to the address.

jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{ 
    q: "Arsenal" 
},function(tweets) { 
    console.info("Twitter returned: ",tweets); 
});

You can also simply use the getScript method:

//In this case, the foo method can also be defined outside the function.
function foo(data){}//Processing data data
$.getJSON('http://www.a.com/user?id=123&callback=foo');

How the ajax method in jquery can be called remotely through JSONP

Parameters of $.ajax

type: Request mode GET/POST

url: Request address

async: Boolean type, which defaults to true to indicate whether the request is asynchronous, and false to synchronize

dataType: The data type returned

Jsonp: The parameter name passed to the request handler or page to obtain the jsonp callback function name (generally default: callback)

jsonpCallback: Custom jsonp callback function name, default to jQuery automatically generated random function name, can also write "?", jQuery will automatically process data for you

success: Call successfully executed functions

error: exception handler

jquery ajax jsonp calls instance code across domains

Both GET and POST can be used to call client code across domains as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function aa() {
        $.ajax({
            url: "http://localhost:12079/WebForm2.aspx",
            data: "p1=1&p2=2&callback=?",
            type: "post",
            processData: false,//The default value of processData is true, which is used to serialize data parameters
            timeout: 15000,
            dataType: "jsonp",  // not "json" we'll parse
            jsonp: "jsonpcallback",
            success: function(result) {
            alert(result.value1);
            }
        });
    }
</script>
</head>
<body>
    <form id="form1" runat="server"><div></div></form>
    <p><input id="Button1" type="button" value="button" onclick="aa()" /></p>
</body>
</html>

Client uses jsonp to transmit data

@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } 
<script type="text/javascript"> 
functionSendData() 
{ 
$.ajax({ 
    type: "get", 
    async: false, 
    url: "/home/ReturnJson", 
    dataType: "jsonp", 
    jsonp: "callback",//The parameter name passed to the request handler or page to obtain the jsonp callback function name (generally default: callback) 
    jsonpCallback: "receive",//Custom jsonp callback function name, default to jQuery automatically generated random function name, can also write "?", jQuery will automatically process data for you 
    success: function(data){ 
        alert(data.name); 
    }, 
    error: function(){ 
        alert('fail'); 
    } 
}); 
} 
functionreceive(data) { 
    alert(data.age); 
} 
</script> 
<input type="button" value="Submission" onclick="SendData();"/> 

When you click the submit button, you find that Request.QueryString["callback"] on the server side returns a random function name. This is set to JSONP format to transfer data.

Topics: JQuery Javascript JSON Attribute