Summary of common Javascript cross-origin requests

Source: Internet
Author: User

Common cross-origin requests in js include four types: window. name, JSONP, jQuery. the first method is to use iframe, the second and third methods use json data, and the last one is xml file operations. Here is a brief introduction.

1. window. name

1. The server returns

The Code is as follows: Copy code

<Script> window. name = '{"id": "3", "name": "leisure"}'; </script>

2. Define an iframe and add an onload event <iframe id = "iframe1" onload = "iLoad"> <iframe>

The Code is as follows: Copy code
<Script type = "text/javascript">
Var load = false;
Function iLoad (){
If (load = false ){
// If the request is processed in the same domain, the iframe will be reloaded again.
Document. getElementById ('iframe1'). contentWindow. location = '/';
Load = true;
} Else {
// Obtain the content of window. name. Note that it must be processed in the same domain before access!
Var data = document. getElementById ('iframe1'). contentWindow. name;
Alert (data); // {"id": "3", "name": "leisure "}
Load = false;
}
}
</Script>

3. Define a form, set the target of the form to the id of iframe, and then submit the form

The Code is as follows: Copy code

<Form action = "url" method = "POST" target = "iframe1">
<Button type = "submit" value = "submit"/>
</Form>

Ii. JSONP

Server return

The Code is as follows: Copy code

Callback ({"id": "3", "name": "leisure "});
<Script type = "text/javascript">
Function callback (data ){
Alert (data );
}
</Script>
<Script type = "text/javascript" src = "http://www.example.com.cn/product.jsp? Id = 5 & jsonp = callback "> </script>

Example

The JSONP format returned by the PHP page should be as follows:

The Code is as follows: Copy code
<? Php
Echo $ _ GET ["callback"].'
(
{
Title: "The Principles of Beautiful Web Design, 2nd Edition ",
Url: "http://www.sitepoint.com/books/design2 ",
Author: "Jason Beaird ",
Publisher: "SitePoint ",
Price :{
Currency: "USD ",
Amount: 39.95
}
}
);
'
?>

For static HTML Request Code, refer to the following:

The Code is as follows: Copy code

<Script language = "javascript" src = "Your URL/zt/access_count/js/jquery-1.4.2.min.js"> </script>
<Script language = "javascript" src = "Your URL/zt/access_count/js/jquery. jsonp-2.1.4.min.js"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
Insert_vote ();
})

Function insert_vote (){
Var j = null;
$. Ajax ({
Type: 'get ',
Url: 'Your url/zt/access_count/jsonp. php ',
DataType: 'jsonp ',
Jsonp: "callback ",
Data: {"a": "insert", "type": "aa", "time": "bb", "id": "dd", "allowVote ": "cc "},
Async: false,
Success: function (data ){
J = data;
// Alert ("1 ");
Alert (j. title );
}
})
}
 
Function init (){
$. Ajax ({
DataType: 'jsonp ',
Data: 'id = 10 ',
Jsonp: 'jsonp _ callback ',
Url: 'Your url/zt/access_count/jsonp. php ',
Success: function ()
{
// Do stuff
Alert (jsonp. respond );
},
});
}

Function init2 (){
$. Ajax ({
Async: false,
Url: 'Your URL/zt/access_count/jsonp. php', // cross-origin url
Type: 'get ',
DataType: 'jsonp ',
Jsonp: 'jsoncallback', // default callback
Data: 'id = 10', // request data
Timeout: 5000,
BeforeSend: function (){
// This method is not triggered in jsonp mode. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event.
},
Success: function (json ){
// The pre-defined callback function of jquery on the client. After the json data on the Cross-origin server is obtained, the callback function is dynamically executed.
Alert (json. respond. title );
If (json. actionErrors. length! = 0)
{
Alert (json. actionErrors );
}
},
Complete: function (XMLHttpRequest, textStatus ){

},
Error: function (xhr ){
// Jsonp mode. This method is not triggered.
// Handle request errors
Alert ("request error (Check related network conditions .)");
}
});
}
</Script>

General method:

The Code is as follows: Copy code

// Initialize the data. The traffic of the same cookie is counted once every minute.
Function init_count (pageType, id ){
Var j = null;
$. Ajax ({
Type: "get", // use the get method to access the background
DataType: "jsonp", // return data in json format
Jsonp: "callback ",
Url: "http://app2.zhnews.net/zt/access_count/manage.php", // The background address to access
Data: {"opp": "main", "pageType": pageType, "id": id },
Async: false,
Success: function (data ){
// Alert (data. total );
// Condition ('{pc_1'{.html (msg. total );
$. Each (data, function (I, v ){
Var tmp = v. record. split (":");
Var month_view = tmp [tmp. length-1];
$ ("Label [id = pc _" + v. page_id + "]" example .html (v. total );
$ ("Label [id = pcm _" + v. page_id + "]" ).html (v. week );
})
}
})
}

Iii. jQuery. getJSON

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

First, let's define the interface specifications, just like this:

Http: // your url/jsonp/ticker? Symbol = IBM & amp; callback = showPrice

Symbol is the request condition, and callback is the name of the callback function.

In the page file, we use JQuery support:

The server returns data in json format test ({"id": "3", "name": "leisure "});

The test function is defined in the callback parameter.

The Code is as follows: Copy code

$. GetJSON (url + "? Callback = ?", Data, function (data ){
}

Example

The Code is as follows: Copy code

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

Note callback =? This parameter must be included. jquery will automatically generate a function name to replace this question mark! JQuery. getJSON is actually implemented using the JSONP method.

Iv. flash cross-OriginAdd crossdomain. xml to the server

The Code is as follows: Copy code

Http://www.example.com.cn/crossdomain.xml

<? Xml version = "1.0"?>
<Cross-domain-policy>
<Allow-access-from domain = "* .another.com.cn"/>
</Cross-domain-policy>

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.