Ajax and Jsonp cross-domain access issues summary _ajax related

Source: Internet
Author: User
Tags http request object model script tag ticket

### #JavaScript的AJax

Ajax is "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML)
An important technique used in designing Ajax is the XMLHttpRequest object.

How to create a XMLHttpRequest object:

XMLHTTP = new Activeobject ("Microsoft.XMLHTTP"); How the IE browser supports creation
XMLHTTP = new XMLHttpRequest (); How to create browser support such as Firefox,opera
XMLHTTP is a set of APIs that can be sent or received from XML and other data via the HTTP protocol in scripting languages such as JavaScript, VbScript, and JScript. Can be used to simulate HTTP GET and post requests.
Can Judge window. The XMLHttpRequest object is available and then the XMLHttpRequest object is created.
The following are the properties and usage of the XMLHttpRequest object, pasted over and commented in detail.

 

To put it simply, you use the XMLHttpRequest object to send a request to the server, and then get the server to return information such a process,
These are the AJAX technical principles of JavaScript. The principle of cross-domain access is completely different from the JSONP that follows.

# # #JQuery的AJax

jquery encapsulates this technology in Ajax, making it easier 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 transform using AJAX. 1. Assemble JSON data. 2. Serialize the contents of the table. var Formparam = $ ("#form1"). Serialize (); 3. Splicing URL ... For example, when we have special strings in our data (such as &), the stitching string is not good, which may make the submission incomplete. The use of JSON in this way will be more useful.

# # #利用jsonp实现跨域访问

What is JSONP?
What's the relationship to 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 visit B station through XMLHttpRequest at station A, which has passed the verification of station B, got the cookie of B station, then we can visit B station at random, At this time a station with B station identity can operate B station all do not need to further verify the operation, this is quite dangerous.

How do we get data across domains?

We found that when we call JS files on a Web page, we are not affected by cross-domain (not only that), but we also find that tags with the attribute "src" have cross-domain capabilities, such as script, IMG, IFRAME, and so on. We can use the nature of JS to get the data we want.

In order to facilitate the use of data by the client, an informal transport protocol has been developed, which is called JSONP, and one of the key points of this protocol is to allow the user to pass a callback parameter to the server, The server side then returns the data by wrapping the callback parameter as the function name to wrap the JSON data so that the client can customize its own function to automatically process the returned data.

Now let's take a look at what Jsonp has done.

1, we know that even in the Cross-domain JS file code (of course, according to the Web Script security Policy), Web pages can also be implemented unconditionally. The remote server remoteserver.com has a remote.js file code below the root directory:

Alert (' I am a remote file ');
The local server localserver.com has a jsonp.html page code as follows:

<! 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 the page will pop up with a prompt form showing the success of Cross-domain calls. This is the most basic jsonp of thought.

2, now we define a function in the Jsonp.html page, and then pass in the data in the remote Remote.js to call. 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 Remote.js file code is as follows:

Localhandler ({"Result": "I am remote JS bring data"});
After running to view the results, the page successfully pop-up prompt window, showing the local function is Cross-domain remote JS call success, and also received the remote JS data brought. The purpose of accessing data across domains has been achieved, but how do I let remote JS know what the name of the local function it should call?

3. You can pass a parameter in the past told the service side "I want a call to the XXX function of the JS code, please return to me," so the server can be in accordance with the needs of the client to generate JS script and response.

<! 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 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 implements encapsulation for JSONP. (Form more like Ajax)

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

Finally, Ajax and JSONP are two completely different things. The core of Ajax is to get non-page content through XMLHttpRequest, and the core of JSONP is to dynamically add script tags to invoke the JS script provided by the server.

How to get data across domains through JSONP in jquery

The first approach is to set datatype as ' Jsonp ' in an AJAX function:

$.ajax ({
    dataType: ' Jsonp ',
    jsonp: ' callback ',
    URL: ' http://www.a.com/user?id=123 ',   
    success: The function (data) {   
        //process data   
    }   
});  

The second approach is to use Getjson to implement, just add callback= to the address of the parameter can be:

$.getjson (' http://www.a.com/user?id=123&callback=? ', function (data) {   
    //process information   
});  

You can also simply use the Getscript method:

In this case, you can also define the Foo method   
function foo (data) {   
    //process data   
}   
$.getjson (' http://www.a.com/user?id=123 &callback=foo ');  

The application of JSONP

The

Jsonp can play a very important role in the Open API, open APIs are used on developers ' own applications, and many applications are often on the developer's server rather than on Sina Weibo's servers, so cross-domain request data is a big problem for developers to solve, The broad open platform should achieve the support of JSONP, this Sina Weibo open platform will do very well (although some APIs are not stated, but in fact can be invoked using JSONP).

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.