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:
- <SCRIPT type = "text/JavaScript">
- // Add the <SCRIPT> label
- Function addscripttag (SRC ){
- VaR script = Document. createelement ('script ');
- Script. setattribute ("type", "text/JavaScript ");
- Script. src = SRC;
- Document. Body. appendchild (SCRIPT );
- }
- Window. onload = function (){
- // Search for Apple and pass the custom callback function name result to the callback parameter.
- Addscripttag ("http://ajax.googleapis.com/ajax/services/search/web? V = 1.0 & Q = apple & callback = Result ");
- }
- // Custom callback function result
- Function result (data ){
- // Obtain the URL data in the first record of the apple search result.
- Alert (data. responsedata. Results [0]. unescapedurl );
- }
- </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
- $. Ajax ({
- Datatype: "jsonp", // datatype for cross-origin access must be of the jsonp type.
- URL: request,
- Type: "Get ",
- Jsonp: "callbackparam ",
- Jsonpcallback: "success ",
- Success: function (response ){
- $ ("# Response URL" ).html ("short address:" + response [0]. url_short );
- },
- Error: function (XMLHttpRequest, textstatus, errorthrown ){
- Alert ("status" + XMLHttpRequest. status );
- Alert ("readystate" + XMLHttpRequest. readystate );
- Alert ("textstatus" + textstatus );
- Alert (errorthrown );
- }
- });
Ajax cross-origin access