Ajax cross-origin access

Source: Internet
Author: User

I. js Ajax cross-origin:

1. Request cross-Origin data by adding the <SCRIPT> tag

2. Use the callback method to obtain data that conforms to the JS syntax.

Sample Code:

  1. <SCRIPT type = "text/JavaScript">
  2. // Add the <SCRIPT> label
  3. Function addscripttag (SRC ){
  4. VaR script = Document. createelement ('script ');
  5. Script. setattribute ("type", "text/JavaScript ");
  6. Script. src = SRC;
  7. Document. Body. appendchild (SCRIPT );
  8. }
  9. Window. onload = function (){
  10. // Search for Apple and pass the custom callback function name result to the callback parameter.
  11. Addscripttag ("http://ajax.googleapis.com/ajax/services/search/web? V = 1.0 & Q = apple & callback = Result ");
  12. }
  13. // Custom callback function result
  14. Function result (data ){
  15. // Obtain the URL data in the first record of the apple search result.
  16. Alert (data. responsedata. Results [0]. unescapedurl );
  17. }
  18. </SCRIPT>

 

Ii. jquery framework Ajax cross-origin:

1. Specify the ype as jsonp; otherwise, the cross-origin is unavailable.

2. Obtain response data in the callback method success

  1. $. Ajax ({
  2. Datatype: "jsonp", // datatype for cross-origin access must be of the jsonp type.
  3. URL: request,
  4. Type: "Get ",
  5. Jsonp: "callbackparam ",
  6. Jsonpcallback: "success ",
  7. Success: function (response ){
  8. $ ("# Response URL" ).html ("short address:" + response [0]. url_short );
  9. },
  10. Error: function (XMLHttpRequest, textstatus, errorthrown ){
  11. Alert ("status" + XMLHttpRequest. status );
  12. Alert ("readystate" + XMLHttpRequest. readystate );
  13. Alert ("textstatus" + textstatus );
  14. Alert (errorthrown );
  15. }
  16. });

 

Ajax cross-origin access

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.