Home  >  Article  >  Web Front-end  >  Detailed explanation of js cross-domain principle and two solutions_javascript skills

Detailed explanation of js cross-domain principle and two solutions_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:26:521551browse

1. What is cross-domain

We often use ajax to request data from other servers on the page. At this time, cross-domain problems will occur on the client.

The cross-domain problem is caused by the same-origin policy in the JavaScript language security restrictions.

Simply put, the same-origin policy means that a script can only read the properties of windows and documents from the same source. The same source here refers to the combination of host name, protocol and port number.

For example:

2. Implementation principle

In the HTML DOM, the Script tag can access data on the server across domains. Therefore, the src attribute of the script can be specified as a cross-domain URL to achieve cross-domain access.

For example:

This access method is not possible. But the following method is possible.

There is a requirement for the returned data, that is: the data returned by the server cannot be simply {"Name":"zhangsan"}

If this json string is returned, we have no way to reference this string. Therefore, the returned value must be var json={"Name":"zhangsan"}, or json({"Name":"zhangsan"})

In order to prevent the program from reporting errors, we must also create a json function.

3. Solution

Option 1
Server side:

protected 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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script type="text/javascript">

    var result = null;
    window.onload = function () {
      var script = document.createElement("script");
      script.type = "text/javascript";
      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>
</head>
<body>
  <input type="button" value="click me!" onclick="b_click();" />
</body>
</html>

Option 2: Complete through jquery

Through jquery’s jsonp method. Using this method has requirements for the server side.

The server side is as follows:

  protected 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({ 
        async: false, 
        url: "http://192.168.0.5/Web/web1.aspx", 
        type: "GET", 
        dataType: 'jsonp', 
        //jsonp的值自定义,如果使用jsoncallback,那么服务器端,要返回一个jsoncallback的值对应的对象. 
        jsonp: 'jsoncallback', 
        //要传递的参数,没有传参时,也一定要写上 
         data: null, 
        timeout: 5000, 
        //返回Json类型 
         contentType: "application/json;utf-8", 
        //服务器段返回的对象包含name,data属性. 
        success: function (result) { 
          alert(result.date); 
        }, 
        error: function (jqXHR, textStatus, errorThrown) { 
          alert(textStatus); 
        } 
      });

Actually, when we execute this js, js sends such a request to the server:

http://192.168.0.5/Web/web1.aspx?jsoncallback=jsonp1354505244726&_=1354505244742

The server also returned the following object accordingly:

jsonp1354506338864({"name":"zhangsan","date":"2012-12-03"})

At this point, the requirements for cross-domain sample data are realized.

The above is an introduction to the js cross-domain principle and two solutions. I hope it will be helpful to everyone in learning cross-domain knowledge points. You can also combine it with other related articles for study and research.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn