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

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

May 16, 2016 pm 03:26 PM

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();
  }

Copy after login

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>

Copy after login

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();
  }

Copy after login

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); 
        } 
      });
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles