Home  >  Article  >  Web Front-end  >  Summary of cross-domain access issues between AJax and Jsonp

Summary of cross-domain access issues between AJax and Jsonp

高洛峰
高洛峰Original
2017-01-09 10:59:211138browse


#JavaScript's AJax


AJAX is "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML)
An important technology used in designing AJax is the XMLHttpRequest object.

How to create an XMLHttpRequest object:


xmlhttp = new ActiveObject("Microsoft.XMLHTTP"); // Creation method supported by IE browser
xmlhttp = new XMLHTTPRequest( ); // Creation method supported by FireFox, Opera and other browsers
XMLHttp is a set of APIs that can transmit or receive XML and other data through http protocol in scripting languages ​​such as Javascript, VbScript, Jscript and so on. Can be used to simulate http GET and POST requests.
You can determine whether the window.XMLHttpRequest object is available and then create an XMLHttpRequest object.

The following are the properties and usage methods of the XMLHttpRequest object. They are pasted and commented in detail.

 
 
XMLHTTPRequest对象的说明DEMO 
 


To put it simply, it is a process of using the XMLHttpRequest object to make a request to the server, and then getting the information returned by the server.

The above is the Ajax technical principle of JavaScript. It is completely different from the principle of Jsonp implementing cross-domain access that will be discussed later.

JQuery's AJax

JQuery encapsulates the ajax technology, making it more convenient to use.

$.General form of ajax

$.ajax({
  type: 'POST',
  url: url ,
  data: data ,
  dataType: dataType
  success: success ,  
});

When the scene is different, we need to use Ajax instead. 1. Assemble json data. 2. Serialize table content. var formParam = $("#form1").serialize(); 3. Splice URLs. . . For example, when there are special strings (such as &) in our data, string splicing is not easy to use, which may make the submitted content incomplete. At this time, it will be easier to use Json.

Using jsonp to achieve cross-domain access


What is Jsonp? What does

have to do with json?

How does jsonp achieve cross-domain access?

First explain why Ajax cannot be accessed across domains and why browsers restrict cross-domain access.

Assuming that the browser supports cross-domain access, we can access site B through XmlHttpRequest at site A. At this time, we have passed the verification of site B and obtained the cookie of site B. Then we can freely When you visit site B, site A can impersonate site B to perform all operations on site B that do not require further verification. This is quite dangerous.

How do we obtain cross-domain data?

We found that when calling js files on a Web page, it is not affected by whether it is cross-domain (not only that, we also found that all tags with the "src" attribute have cross-domain capabilities, such as script, img, iframe, etc. We can use this property of js to obtain the data we want.

In order to facilitate the client to use data, an informal transmission protocol has gradually formed. People call it JSONP. One of the key points of this protocol is to allow users to pass a callback parameter to the server. Then when the server returns data, it will use this callback parameter as a function name to wrap the JSON data, so that the client can customize it at will. Use your own function to automatically process the returned data.

Let’s take a look at what jsonp does.


1. We know that even cross-domain js files. The code in (of course it complies with the web script security policy), the web page can also be executed unconditionally. There is a remote.js file in the root directory of the remote server remoteserver.com with the following code:

alert('I am Remote file');

The local server localserver.com has a jsonp.html page code as follows:




  
  

There is no doubt that a prompt form will pop up on the page, indicating that the cross-domain call is successful. This is the most basic idea of ​​jsonp.

2. Now we define a function in the jsonp.html page, and then call it by passing in data in the remote remote.js. The jsonp.html page code is as follows:




  
  
  


remote.js file code is as follows:

localHandler({"result":"I am the data brought by remote js"});

Check the result after running, the page will pop up a prompt window successfully , showing that the local function was successfully called by the cross-domain remote js, and the data brought by the remote js was received. The purpose of cross-domain access to data has been achieved, but how do I let the remote js know the name of the local function it should call? What?

3. You can pass a parameter to tell the server "I want a js code that calls the XXX function, please return it to me", so the server can generate the js script according to the client's needs. Responded.




  
  


On the server side, we get the callback and assemble the required js.

String callback = request.getParemeter("callback");

response.getWriter. print(callback + "(" + json +")");

The content returned to the page is:

flightHandler({
  "code": "CA1998",
  "price": 1780,
  "tickets": 5
});

4.Jquery also encapsulates jsonp. (The form is more like ajax)


 
 
   Untitled Page
   
   
   

Finally, Ajax and jsonp are two completely different things. The core of ajax is to obtain non-this page content through XmlHttpRequest, while the core of jsonp is to dynamically add script tags to call the js script provided by the server.

How to obtain cross-domain data through JSONP in jQuery

######The first method is to set the dataType to 'jsonp' in the ajax function: ###
$.ajax({
    dataType: 'jsonp',
    jsonp:'callback',
    url: 'http://www.a.com/user?id=123',   
    success: function(data){   
        //处理data数据   
    }   
});

第二种方法是利用getJSON来实现,只要在地址中加上callback=?参数即可:

$.getJSON('http://www.a.com/user?id=123&callback=?', function(data){  
    //处理data数据  
});

   

也可以简单地使用getScript方法:

//此时也可以在函数外定义foo方法  
function foo(data){  
    //处理data数据  
}  
$.getJSON('http://www.a.com/user?id=123&callback=foo');

   

JSONP的应用

JSONP在开放API中可以起到非常重要的作用,开放API是运用在开发者自己的应用上,而许多应用往往是在开发者的服务器上而不是在新浪微博的服务器上,因此跨域请求数据成为开发者们所需要解决的一大问题,广大开放平台应该实现对JSONP的支持,这一点新浪微博开放平台便做的非常好(虽然某些API里没有说明,但实际上是可以使用JSONP方式调用的)。

更多AJax与Jsonp跨域访问问题小结相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn