Ajax cross-origin request

Source: Internet
Author: User

Asynchronous JavaScript and XML (Ajax) Is a key technology driving the next generation of web sites (commonly referred to as Web 2.0 sites. Ajax allows data retrieval in the background without interfering with the display and behavior of Web applications. UseXMLHttpRequestA function is an API that allows the client JavaScript to connect to a remote server over HTTP. Ajax is also the driving force of many MashUps, which can integrate content from multiple places into a single web application.

 

However, due to browser restrictions, this method does not allow cross-origin communication. If you try to request data from different domains, a security error occurs. If you can control the remote server where data resides and each request is sent to the same domain, you can avoid these security errors. However, what is the use of web applications if they only stay on their own servers? What should I do if I need to collect data from multiple third-party servers?

 

Understanding same-origin policy restrictions

The same-origin policy prevents scripts loaded from one domain from obtaining or operating on document properties in another domain. That is to say, the domain of the requested URL must be the same as that of the current web page. This means that the browser isolates content from different sources to prevent operations between them. This browser policy is old and has existed since Netscape Navigator 2.0.

 

A relatively simple way to overcome this limitation is to request data from a web page to the Web server it originated from, and let the Web server forward the request to a real third-party server like a proxy. Although this technology is widely used, it cannot be scaled. Another way is to use the framework element to create a region in the current web page and useGETRequest to obtain any third-party resources. However, after obtaining resources, the content in the framework will be restricted by the same-source policy.

 

An ideal way to overcome this restriction is to insert a dynamic script element into the web page. The page source points to the service URL in another domain and obtains data in its own script. When the script is loaded, it starts to execute. This method is feasible because the same-origin policy does not prevent dynamic script insertion and regards the script as being loaded from the domain that provides the web page. However, if the script tries to load the document from another domain, it will not succeed. Fortunately, this technology can be improved by adding JavaScript Object Notation (JSON.

 

1. What is jsonp?

 

To understand jsonp, I have to mention JSON. What is JSON?

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

Jsonp (JSON with padding) is an unofficial protocol that allows the server to integrate SCRIPT tags to return to the client, cross-origin access is implemented through javascript callback (this is only a simple implementation form of jsonp ).

 

2. What is jsonp used?

Due to the restrictions of the same-origin policy, XMLHttpRequest only allows requests to resources of the Current Source (domain name, protocol, Port). To implement cross-origin requests, you can use the script tag to implement cross-origin requests, then, the server outputs JSON data and executes the callback function to resolve cross-Origin data requests.

 

3. How to Use jsonp?

The demo below is actually a simple form of jsonp. After the client declares the callback function, the client uses the script tag to request data from the server across domains, then the server returns the corresponding data and dynamically executes the callback function.

 

HTML code (any ):

 

HTML code
  1. <Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/>
  2. <SCRIPT type = "text/JavaScript">
  3. Function jsonpcallback (result ){
  4. // Alert (result );
  5. For (var I in result ){
  6. Alert (I + ":" + result [I]); // cyclically Output A: 1, B: 2, etc.
  7. }
  8. }
  9. VaR jsonp = Document. createelement ("script ");
  10. Jsonp. type = "text/JavaScript ";
  11. Jsonp. src = "http://crossdomain.com/services.php? Callback = jsonpcallback ";
  12. Document. getelementsbytagname ("head") [0]. appendchild (jsonp );
  13. </SCRIPT>
<Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/> <SCRIPT type = "text/JavaScript"> function jsonpcallback (result) {// alert (result); For (var I in result) {alert (I + ":" + result [I]); // cyclically Outputs A: 1, B: 2, etc .}} vaR jsonp = document. createelement ("script"); jsonp. type = "text/JavaScript"; jsonp. src = "http://crossdomain.com/services.php? Callback = jsonpcallback "; document. getelementsbytagname (" head ") [0]. appendchild (jsonp); </SCRIPT>

Or

 

HTML code
  1. <Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/>
  2. <SCRIPT type = "text/JavaScript">
  3. Function jsonpcallback (result ){
  4. Alert (result. );
  5. Alert (result. B );
  6. Alert (result. C );
  7. For (var I in result ){
  8. Alert (I + ":" + result [I]); // cyclically Output A: 1, B: 2, etc.
  9. }
  10. }
  11. </SCRIPT>
  12. <SCRIPT type = "text/JavaScript" src = "http://crossdomain.com/services.php? Callback = jsonpcallback "> </SCRIPT>
<Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/> <SCRIPT type = "text/JavaScript"> function jsonpcallback (result) {alert (result. a); alert (result. b); alert (result. c); For (var I in result) {alert (I + ":" + result [I]); // cyclically Outputs A: 1, B: 2, etc .}} </SCRIPT> <SCRIPT type = "text/JavaScript" src = "http://crossdomain.com/services.php? Callback = jsonpcallback "> </SCRIPT>

 

The javascript link must be under the function.

 

Server PHP code (services. php ):

 

PHP code
  1. <? PHP
  2.  
  3. // JSON data returned by the server
  4. $ Arr = array ('A' => 1, 'B' => 2, 'c' => 3, 'D' => 4, 'E' => 5 );
  5. $ Result = json_encode ($ ARR );
  6. // Echo $ _ Get ['callback']. '("Hello, world! ")';
  7. // Echo $ _ Get ['callback']. "($ result )";
  8. // Dynamically execute the callback function
  9. $ Callback = $ _ Get ['callback'];
  10. Echo $ callback. "($ result )";
<? PHP // JSON data returned by the server $ arr = array ('A' => 1, 'B' => 2, 'c' => 3, 'D' => 4, 'E' => 5); $ result = json_encode ($ ARR); // echo $ _ Get ['callback']. '("Hello, world! ") '; // Echo $ _ Get ['callback']. "($ result)"; // The callback function $ callback =$ _ Get ['callback']; echo $ callback. "($ result )";

If you use jquery to implement the above JS client code, it is also very simple.

 

$. Getjson $. Ajax $. Get

 

Implementation Method 1 of client JS Code in jquery:

 

JS Code
  1. <SCRIPT type = "text/JavaScript" src = "jquery. js"> </SCRIPT>
  2. <SCRIPT type = "text/JavaScript">
  3. $. Getjson ("http://crossdomain.com/services.php? Callback =? ",
  4. Function (result ){
  5. For (var I in result ){
  6. Alert (I + ":" + result [I]); // cyclically Output A: 1, B: 2, etc.
  7. }
  8. });
  9. </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "jquery. js"> </SCRIPT> <SCRIPT type = "text/JavaScript"> $. getjson ("http://crossdomain.com/services.php? Callback =? ", Function (result) {for (var I in result) {alert (I +": "+ result [I]); // cyclically Outputs A: 1, B: 2, etc .}}); </SCRIPT>

Implementation Method 2 of client JS Code in jquery:

 

JS Code
  1. <SCRIPT type = "text/JavaScript" src = "jquery. js"> </SCRIPT>
  2. <SCRIPT type = "text/JavaScript">
  3. $. Ajax ({
  4. URL: "http://crossdomain.com/services.php ",
  5. Datatype: 'jsonp ',
  6. Data :'',
  7. Jsonp: 'callback ',
  8. Success: function (result ){
  9. For (var I in result ){
  10. Alert (I + ":" + result [I]); // cyclically Output A: 1, B: 2, etc.
  11. }
  12. },
  13. Timeout: 3000
  14. });
  15. </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "jquery. JS "> </SCRIPT> <SCRIPT type =" text/JavaScript "> $. ajax ({URL: "http://crossdomain.com/services.php", datatype: 'jsonp', data: '', jsonp: 'callback', success: function (result) {for (var I in result) {alert (I + ":" + result [I]); // cyclically Outputs A: 1, B: 2, etc .}}, timeout: 3000}); </SCRIPT>

Implementation Method 3 of client JS Code in jquery:

 

JS Code
  1. <SCRIPT type = "text/JavaScript" src = "jquery. js"> </SCRIPT>
  2. <SCRIPT type = "text/JavaScript">
  3. $. Get ('HTTP: // crossdomain.com/services.php? Callback =? ', {Name: encodeuricomponent ('tester')}, function (JSON) {for (var I in JSON) Alert (I + ": "+ JSON [I]) ;}, 'jsonp ');
  4. </SCRIPT>
<script type="text/javascript" src="jquery.js"></script><script type="text/javascript">$.get(‘http://crossdomain.com/services.php?callback=?‘, {name: encodeURIComponent(‘tester‘)}, function (json) { for(var i in json) alert(i+":"+json[i]); }, ‘jsonp‘);</script>

Among them, jsoncallback is registered by the client. After obtaining JSON data on the Cross-origin server, it calls back the function. Http://crossdomain.com/services.php? Callback = jsonpcallback this URL is the interface for the cross-origin server to retrieve JSON data. The parameter is the name of the callback function and the returned format is

 

JS Code
  1. Jsonpcallback ({MSG: 'This is JSON data '})
jsonpCallback({msg:‘this is json data‘})

Jsonp principle:Register a callback on the client, and then pass the callback name to the server.
In this case, the server is converted into JSON data. Then, a function is generated in Javascript syntax. The function name is the passed parameter jsonp.
Finally, place the JSON data directly in the function as an input parameter. In this way, a JS syntax document is generated and returned to the client.
The client browser parses the script tag and executes the returned JavaScript document. As a parameter, the data is passed into the pre-defined callback function of the client. (The callback function is dynamically executed)

 

JSON has the following advantages:

  • It is much lighter than XML, and there is not so much redundancy.
  • JSON is also readable, but usually the returned results are compressed. Unlike browsers like XML, the browser can directly display JSON format. Some plug-ins are required for browser formatting.
  • Processing JSON in Javascript is simple.
  • Other languages such as PHP have good support for JSON.

JSON also has some disadvantages:

  • JSON is not widely supported as XML on the server side, but json.org provides libraries in many languages.
  • If you use eval () for parsing, security issues may occur.

However, the advantages of JSON are obvious. He is an ideal data format for Ajax data interaction.

 

TIPS:

Jsonp is a powerful technique for building mashup, but unfortunately it is not a panacea for all cross-domain communication needs. It has some defects and must be carefully considered before submitting development resources.

 

First, and most importantly, there is no error handling for jsonp calls. If the dynamic script insertion is valid, the call is executed. If the dynamic script insertion is invalid, the silent operation fails. There is no prompt for failure. For example, a 404 error cannot be captured from the server, or the request cannot be canceled or restarted. However, if you haven't responded for a while, you don't have to worry about it. (In future jquery versions, the jsonp request may be terminated ).

 

Another major defect of jsonp is that it is dangerous to be used by untrusted services. Because the jsonp service returns the JSON response packaged in the function call, and the function call is executed by the browser, the host web application is more vulnerable to various attacks. If you plan to use the jsonp service, it is very important to understand the threats it can cause.

From: http://justcoding.iteye.com/blog/1366102days ladder dream

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.