JS cross-Domain and solutions

Source: Internet
Author: User

1. What is a cross-domain

We often use Ajax on the page to request access to data from other servers, where there are cross-domain issues for the client.

Cross-domain issues are caused by the same-origin policy in JavaScript language security restrictions.

In simple terms, the same origin policy refers to a script that can read only the properties of windows and documents from the same source, where the same source refers to a combination of host names, protocols, and port numbers.

For example:

same domain name, different port
URL Description whether to allow communication
http://www.a.com/a.js
http://www.a.com /b.js
under the same domain name allow
http://www.a.com/lab/a.js
http://www.a.com/script/b.js
different folders under the same domain name allow
http://www.a.com:8000/a.js
http://www.a.com/b.js
does not allow
http://www.a.com/a.js
https://www.a.com/b.js
same domain name, different protocol /td> not allowed
http://www.a.com/a.js
http://70.32.92.74/b.js
domain name and domain name corresponding IP Do not allow
http://www.a.com/a.js
http://script.a.com/b.js
primary domain same, subdomain different not allowed
http://www.a.com/a.js
http://a.com/b.js
same domain name, different level two domain name (ibid.) not allowed (cookies are not allowed in this case Q)
http://www.cnblogs.com/a.js
http://www.a.com/b.js
different domain names do not allow

2. Principle of implementation

In the HTML DOM, a script tag is a cross-domain access to the data on the server. Therefore, you can specify the SRC attribute of the script as a cross-domain URL for cross-domain access.

For example:

This type of access is not possible. But the following is a good way to do it.

<script src= "http://192.168.0.5/Web/web1.aspx" type= "Text/javascript" ></script>

There is a requirement for the returned data, that is, the data returned by the server cannot be simple as {"Name": "Zhangsan"}

If this JSON string is returned, there is no way to reference the string. Therefore, the value to be returned must be var json={"name": "Zhangsan"}, or JSON ({"name": " Zhangsan "})

In order to make the program not error, we must also establish a JSON function.

3. Solution

Programme I

Server-side:

        void Page_Load (object sender, EventArgs e)        {            string result = "callback ({\" name\ ": \" zhangsan\ ", \" Date\ ": \" 2012-12-03\ "})";            Response.Clear ();            Response.Write (result);            Response.End ();        }  

Client:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en ""Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">http://www.w3.org/1999/xhtml ">Text/javascript "> var result = null; Window.onload = function () {var script = document.createelement ("script"); script.type = "text/javasc Ript "; SCRIPT.SRC = "http://192.168.0.101/ExampleBusinessApplication.Web/web2.aspx"; var head = document.getElementsByTagName ("head") [0]; Head.insertbefore (script, head.firstchild);}; function callback (data) {result = data;} function B_click () {alert (result.name);} </script>button" value= "clickme!" onclick= "B_click();"/></body>

Scenario two, complete with jquery

Through the Jsonp of jquery. Using this approach, there are requirements for the server side.

The server side is as follows:

        void Page_Load (object sender, EventArgs e)        {            string callback = request.querystring["jsoncallback" ];            string result = Callback + "({\" name\ ": \" zhangsan\ ", \" date\ ": \" 2012-12-03\ "})"; Response.Clear (); Response.Write (Result); Response.End (); }

Client:

$.ajax ({
AsyncFalse
URL: "http://192.168.0.5/Web/web1.aspx ",
Type: "GET ",
DataType: ' Jsonp ',
Jsonp the value of the custom, if using Jsoncallback, then the server side, to return a jsoncallback value corresponding to the object.
JSONP: ' Jsoncallback ',
To pass the parameter, do not pass the argument, also must write on
DataNull
timeout:5000,
Return JSON type
ContentType: "Application/json;utf-8 ",
The object returned by the server segment contains the Name,data property.
Successfunction (Result) {
                     alert (Result.date);
               },
                 Error: function (JQXHR, Textstatus, Errorthrown) {
                     alert (Textstatus);
               }
           });

In fact, when we execute this JS, JS sends a request to the server:

Http://192.168.0.5/web /web1.aspx?jsoncallback=jsonp1354505244726&_=1354505244742

The server also returns the following object:

 jsonp1354506338864 ({"name": "zhangsan", "date ":" 2012-12-03 "})     
The requirements for cross-domain sample data are implemented at this time.

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.