Summary of cross-origin access between AJax and Jsonp,

Source: Internet
Author: User

Summary of cross-origin access between AJax and Jsonp,

#### JavaScript AJax

AJAX is "Asynchronous Javascript And XML" (Asynchronous JavaScript And XML)
An important technique used to design AJax is the XMLHttpRequest object.

How to create an XMLHttpRequest object:

Xmlhttp = new ActiveObject ("Microsoft. XMLHTTP"); // creation method supported by IE
Xmlhttp = new XMLHTTPRequest (); // Creation supported by FireFox, Opera, and other browsers
XMLHttp is a set of APIs that can be transmitted over http or receive XML and other data in Javascript, VbScript, Jscript, and other scripting languages. It 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 attributes and usage of the XMLHttpRequest object are as follows, which are pasted and annotated in great detail.

<Html> 

Simply put, the XMLHttpRequest object is used to send a request to the server and then obtain the server's returned information,
The above are the technical principles of JavaScript Ajax. The principle of implementing cross-origin access with Jsonp is totally different from that described later.

### JQuery AJax

JQuery encapsulates ajax technology, making it easier to use.

$. General ajax format

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

In different scenarios, we need to use Ajax instead. 1. Assemble json data. 2. serialize the table content. Var formParam = $ ("# form1"). serialize (); 3. Splice URL... For example, when we have special strings (for example, &) in our data, splicing strings may make the submitted content incomplete. In this case, the Json format is better.

### Use jsonp for cross-origin access

What is Jsonp?
What is the relationship with json?
How does jsonp implement cross-origin access?

First, Let's explain why Ajax cannot be accessed across domains, and why does the browser limit cross-domain access.

Assuming that the browser supports cross-origin access, we can access site B through XmlHttpRequest on Site A. At this time, we have passed Site B's verification and obtained Site B's Cookie, then we can access site B at will. At this time, Station A can use the identity of Site B to perform operations that do not require further verification. This is quite dangerous.

How can we obtain cross-Origin data?

We found that when calling js files on the web page, it is not affected by cross-origin (In addition, we also found that all tags with the "src" attribute have cross-origin capabilities, for example, script, img, iframe, and so on. We can use this property of js to obtain the data we want.

To facilitate the use of data on the client, an informal transmission protocol is gradually formed, which is called JSONP. One of the main points of this Protocol is to allow users to pass a callback parameter to the server, then, when the server returns the data, the callback parameter is wrapped in JSON data as the function name, so that the client can customize its own function to automatically process the returned data.

Let's take a look at what jsonp has done.

1. We know that even the code in the Cross-origin js file (of course, that complies with the web script Security Policy) can be executed unconditionally on the web page. The remote server remoteserver.com root directory contains the following remote. js file code:

Alert ('am a remote file ');
The following figure shows the jsonp.html Page code of the worker server localserver.com:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

There is no doubt that a prompt form will pop up, showing that the cross-origin call is successful. This is the most basic idea of jsonp.

2. Now we define a function on the jsonp.html page, and then input data in remote. js for calling. The jsonp.html Page code is as follows:

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

The code of the remote. js file is as follows:

LocalHandler ({"result": "data from remote js "});
View the result after running. A Prompt window is displayed, indicating that the local function is successfully called by the cross-origin remote js and that the data of the remote js is received. The purpose of cross-Origin data access has been achieved, but how can I let remote js know the name of the local function that should be called?

3. you can pass a parameter to the server and tell the server "I want a js Code that calls the XXX function. Please return it to me ", as a result, the server can generate js scripts and respond to the requirements of the client.

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

On the server side, we get 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 implements encapsulation for jsonp. (The form is more like ajax)

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

Finally, I declare that Ajax and jsonp are two completely different things. The core of ajax is to obtain content not on this page through XmlHttpRequest, while the core of jsonp is to dynamically Add the script tag to call the js script provided by the server.

How to Use JSONP in jQuery to obtain data across domains

The first method is to set ype to 'jsonp' In the ajax function ':

$. Ajax ({dataType: 'jsonp', jsonp: 'callback', url: 'http: // www.a.com/user? Id = 123 ', success: function (data) {// process data }});

The second method is to use getJSON to add callback =? Parameters:

$. GetJSON ('HTTP: // www.a.com/user? Id = 123 & callback =? ', Function (data) {// process data });

You can also simply use the getScript method:

// You can also define the foo method function foo (data) {// process data} $. getJSON ('HTTP: // www.a.com/user? Id = 123 & callback = foo ');

JSONP Application

JSONP can play a very important role in open APIs. Open APIs are used in developers' own applications, many applications are often deployed on developer servers rather than Sina Weibo servers. Therefore, cross-origin request data has become a major problem that developers need to solve, the majority of open platforms should support JSONP, which is very good for Sina Weibo open platforms (although some APIs are not described, they can actually be called using JSONP ).

Articles you may be interested in:
  • How to implement cross-origin access using jsonp in jquery
  • Use of ajax jsonp for cross-origin requests
  • Jsonp restrictions in jquery ajax
  • Jquery ajax jsonp cross-origin call instance code
  • Use jQuery and JSONP to easily solve cross-origin access problems
  • How to remotely call ajax methods in jquery through JSONP
  • Differences between JSON and JSONP and the use of jQuery ajax jsonp
  • JSONP cross-origin GET requests solve Ajax cross-origin access problems

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.