Use JSONP to solve cross-Origin data access problems

Source: Internet
Author: User

Introduction

One obvious feature of many websites that meet the Web characteristics is Ajax. Ajax provides the ability to submit requests to access data in the background. The implementation mainly uses the XMLHttpRequest function, which allows the client's Javascript

Send an HTTP request to the server and obtain the returned data. Ajax is also the driving force behind many mashups. They all use Ajax to aggregate information from different sources.

Understanding the limitations of same-origin policy

The same-origin policy prevents code from obtaining or modifying files or information obtained from another domain name. That is to say, our request address must be the same as that of the current website. The same-origin policy protects resources by isolation. This strategy has a long history
The era of Netscape Navigator 2.0 has started.

A relatively simple solution to this limitation is to send requests on the server side, and the server acts as a proxy relay to reach third-party resources. Although widely used, this method is not flexible enough.

Another method is to use the framework (frames) to include resources of third-party sites, but the resources included are also subject to the same-source policy restrictions.

One clever way is to use dynamic code elements on the page. The source of the code points to the service address and loads data in your own code. When the code is loaded and executed, the same-source policy will not limit the execution. However, if the code tries to download an object
Execution will still fail. Fortunately, we can use JSON (JavaScript Object Notation) to improve this application.

JSON and JSONP

JSON is a lightweight data exchange format compared with XML. JSON is attractive to JavaScript developers because JSON itself is an object in Javascript.

For example, a ticker object
Var ticker = {symbol: 'ibm ', price: 100}

The JSON string is {symbol: 'ibm ', price: 100}

In this way, JSON data can be transmitted in the function parameters. We can easily grasp the use of dynamic JSON parameter data in functions, but our goal is not this.

By enabling our functions to load Dynamic JSON data, we can process Dynamic data. This technology is called Dynamic Javascript Insertion.

Let's look at the example below.
Index.html

Ticker. js
Var data = {symbol: 'ibm ', price: 100 };
ShowPrice (data );

The above code dynamically adds Javascript code to execute functions to load data.
As mentioned earlier, the same-origin policy is not applicable to dynamically inserted code. That is, you can load code from different domains to execute JSON data in their code.

This is JSONP (JSON with Padding ). Note: When using this method, you must define the callback function on the page, just like showPrice in the previous example.

The JSONP Service (Remote JSON service) is actually an extended capability to include returned data in user-defined functions. This method relies on accepting the name of a callback function as a parameter.

Then execute this function to process JSON data and display it on the customer page.

JSONP support of JQuery

JQery 1.2 and later support JSONP calls. Specify the callback function name in another domain name. You can load JSON data in the following format.

Url? Callback =?
Example:
JQuery. getJSON (url + "& callbak =? ", Function (data ){
Alert ("Symbol:" + data. symbol + ", Price:" + data. price );
});

Jquery loads a global function in the window object. When the code is inserted, the function is executed and removed after execution. At the same time, jquery also optimizes non-Cross-origin requests. If the request is under the same domain name, it will work like a normal Ajax request.

In the above example, static json data is used in the code dynamically inserted into the page. Although JSONP is returned in sequence, it is still not a JSONP service, because callback function names cannot be defined in URLs. The following is a method for turning it into a JSONP service.
The server uses PHP.

First let's define the interface specification, like this: http://www.mydomain.com/jsonp/ticker? Symbol = IBM & callback = showPrice
Symbol is the request condition, and callback is the name of the callback function.

In the page file, we use JQuery support:

// JQuery JSONP Support
Var url = "http://www.mydomain.com/api/suggest.php? Symbol = IBM & callback =? ";
JQuery. getJSON (url, function (data ){
Alert ("Symbol:" + data. symbol + ", Price:" + data. price );
});

In suggest. php
$ Jsondata = "{symbol: 'ibm ', price: 120 }";
Echo $ _ GET ['callback']. '('. $ jsondata .')';

Now, if we want to create some mashups or integrate third-party resources into a page, we can easily think of the JSONP solution.

Existing JSONP services

Now that we know how to use JSONP, we can use some existing JSONP services. Below are some examples:

Digg API: http://services.digg.com/stories/top? Appkey = http % 3A % 2F % 2Fmashup.com & type = javascript & callback =?
Geonames API: http://www.geonames.org/postalCodeLookupJSON? Postalcode = 10504 & country = US & callback =?
Flickr API: http://api.flickr.com/services/feeds/photos_public.gne? Tags = cat & tagmode = any & format = json & jsoncallback =?

Note:

JSONP is a very powerful method for building mashp, but it is not a panacea for cross-origin access problems. It also has some disadvantages

First and foremost: JSONP does not provide error handling. If the dynamically inserted code runs normally, you can get a response, but if it fails, nothing will happen. You cannot get a 404 error or cancel the request. Another important drawback is that the use of untrusted services poses a great security risk.

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.