JavaScript gets JSON data across domains

Source: Internet
Author: User
Tags script tag

Project in the development process, the use of the weather forecast function, so you need to invoke the weather forecast API, the first thought directly with the AJAX call URL can get weather data, the result involves cross-domain problem, here to do a record.

When it comes to cross-domain, you need to know the same origin strategy .

The homologous strategy (same origin policy) is a well-known security policy proposed by Netscape. This policy is now used by all JavaScript-enabled browsers. The so-called homology refers to the same domain name, protocol, and port. It is the core of the browser and the most basic security features, if the absence of the same-origin policy, the browser's normal functionality may be affected. It can be said that the Web is built on the basis of the same origin policy, the browser is only for the same origin of the implementation of the policy. The same-origin policy means that scripts on the page cannot access non-homologous resources (including HTTP responses and cookies)

Why should we have a homologous strategy? Popular Science: XSS attacks browser-origin policy and cross-domain access

Cross-Domain (Cross-domain): Violates the same-origin policy, that is, the domain name, protocol, port is not exactly the same, JS can not carry out line data transmission or communication.

Cross-domain error hint: Origin XX is not allowed by access-control-allow-origin error reason:

To resolve a cross-domain approach:

1. Cross-domain implementation via JSONP

Although the browser prohibits cross-domain access by default, it does not prohibit referencing other domain's JS files in the page (not only that, we also find that all tags that have the attribute "src" have cross-domain capabilities such as <script>, , <iframe >), and can freely execute the function in the introduced JS file (including manipulating cookies, DOM, etc.). Based on this, it is convenient to create a script node to achieve complete cross-domain communication . JSONP is the use of this feature to achieve.

The data source API for my weather forecast is provided by the Baidu API store, and the returned data is in JSON format. Weather information varies based on the logged-on user's information, so the node where the script is added needs to be added dynamically.

Here's a question: How is the dynamically added script node destroyed?

jquery's Ajax implementation across domains

Because the project uses the jquery framework, it is possible to implement the cross-domain directly with jquery ajax or Getjson. According to the jquery API introduction (http://api.jquery.com/jQuery.getJSON/#urldatacallback), Getjson is just a simplified way of writing the Ajax of query. The principle of using jquery's AJAX implementation to add script across domains and yourself is just the same, except that we don't need to manually insert a script tag and define a callback function. jquery automatically generates a global function to replace the question mark in callback=, which is then automatically destroyed after the data is obtained, in effect, as a temporary proxy function. The $.getjson method automatically determines whether a cross-domain, non-cross-domain, calls a normal Ajax method, or cross-domain, invokes the JSONP callback function in the form of an asynchronously loaded JS file. Reference: http://www.cnblogs.com/know/archive/2011/10/09/2204005.html

 $.ajax ({type: "GET", url: "Http://api.duoshuo . com/threads/counts.jsonp?short_name=official&threads=4ff1cbc43ae636b72a00001d ", Error:function (XMLHt                    Tprequest, Textstatus, Errorthrown) {alert (textstatus);                    alert (Errorthrown); This The options parameter passed when calling this Ajax request}, DataType: "Jsonp", Success:function (msg, text Status) {alert (' OK ')}}) 

Baidu Apistore Weather API and support JSONP, so when I request data in the above way, the returned data is still JSON, not the callback function (JSON) format, so the callback function cannot be executed, at this time the error prompt is: uncaught Syntax error:unexpected token: ..., this is because the server returned to the JSON data directly into the script tag, and so on when the script tag is loaded, the response JSON as JS to execute immediately, it is obvious {"Errnum": 0, " ErrMsg ":" Success "," Retdata ": {" City ":" \u5317\u4eac "," Pinyin ":" Beijing "," Citycode ":" 101010100 "," date ":" 15-03-03 " , "Time": "Postcode", "the": "100000", "Longitude": 116.391, "latitude": 39.904, "altitude": "", "Weather": "\u6674", " Temp ":" 4 "," L_tmp ":" 4 "," H_tmp ":" 4 "," WD ":" \u5317\u98ce "," WS ":" 5-6\u7ea7 (25~34m\/h) "," Sunrise ":" 06:45 "," Sunset ": "18:07"} is not a valid JS statement, error occurred

2. using HTML5 postMessage

Not to be continued

Reference Documents:

[1] http://www.cnblogs.com/chopper/archive/2012/03/24/2403945.html

[2] Http://www.cnblogs.com/know/archive/2011/10/09/2204005.html

[3] Http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html#m0

[4] Http://www.cnblogs.com/2050/p/3191744.html

[5] Http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html

JavaScript gets JSON data across domains

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.