Implementation of Ajax cross domain request to obtain ajax data in web pages based on iframe

Time:2020-10-15

As we all know, AJAX requests cannot be sent in different domains. The browser will report the following error:

At the same time, there is no cross domain communication in the embedded iframes, which means that iframes in different domains can’t read data from each other (of course, data can be transferred from the parent window to the child iframes by using hash changes, but it doesn’t make sense). When iframe communicates across domains, the browser will report the following error:

In fact, these two problems are caused by cross domain.

Here is how to solve this problem

In fact, the key to the problem is that the browser will compare the address of the current web page when parsing the Ajax request address. If it is cross domain, it will be prohibited and an error will be reported. So if we let the browser resolve the same Ajax address as the current web page, the browser will not prohibit our request.

So how do browsers parse URLs?

First of all, when the browser visits a domain name, it will query the local DNS cache whether there is an IP address corresponding to the address. If there is, the browser will directly obtain the IP address from the local and then visit. If not, the browser will send a DNS request to the DNS server to obtain the IP address corresponding to the domain name, and then store it in the local cache and then access.

In view of the above problems, we only need to forge a domain name resolution method locally, and then make cross domain requests through the forged domain and the target domain.

Open C under Windows: Windows / system32 / Drivers / etc
There is a hosts file under this folder. If you change hosts to Google, you should be familiar with it. Add this code to the hosts file:

127.0.0.1 A. target website.com

In this way, your visit to A. target website. Com is the same as visiting localhost. The purpose of this is to facilitate the setting up of local services, and there will be no cross domain problem between the local service and the target domain name. In this way, you can initiate cross domain requests to the target domain and obtain the data of the target domain by implanting an iframe label on the target web page locally.

Code directly (with jQuery)

Script code, directly inserted in the parent domain

var mySrc = " http://a. Target address com:9000/myIframe.html ";

document.domain  ="Target URL. Com"; // key code to promote the domain to the root domain

$("body"). Append ('< iframe SRC =' + mysrc + 'name = "myiframe" > < / frame >'); // insert iframe into the target web page

var interval;

function start() {
 $("#getData").attr({"src": mySrc});
 interval = setInterval(function() {
  window.myIframe.run (getlogic); // pass in the callback function to the subdomain  
 },10000)
}

function stop() {
 clearInterval(interval);
}

function getLogitic(orderId) {
 $.ajax({
  url: '/query?'+ orderId +'&id=1&valicode=&temp=' + Math.random(),
  method: 'GET',
  success: function(res) {
   console.log (RES); // you can call the subdomain method here to transfer data to the local file
  },
  error: function(err) {
   console.log('err: ', err);
  }
 })
}

HTML code in iframe

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <script src="bower_components/jquery/dist/jquery.js"></script>
 <script>
  document.domain  ="Target URL. Com"; // key code to promote the subdomain to the root domain
  var int;
  function run(callback) {
  //This request is used to request data from the local, and then according to the local data, use the callback function from the parent domain to send a request to the target domain to get the data of the target domain 
   $.ajax({
    url: './ getOrderList.json "// where the local data is stored, lazy and directly write a JSON file, which can be the data in the database
    method: 'GET',
    success: function(res) {
     var data = res.list;
     int = setInterval(function(){
      Callback (data [0]); // execute the callback function passed in from the parent domain
      data.shift();
      if (data.length === 0) clearInterval(int);
     }, 1000);
    },
    error: function(err) {
     console.log(err)
    }
   })
  }
 </script>
</body>
</html>

be careful:

Only if the iframe is promoted to the root domain, can it communicate with the parent window document.domain The instruction can only promote the current domain to the current root domain, which is the reason why the local hosts file must be modified, which is the root of solving the cross domain problem.
Before grabbing the data of the target web page, we should first look at the way the target page sends the Ajax request, get the API of the request, insert the script through the console of the target page, and then run it to get the data to be obtained, and send it to the local through and local request.
The following is the process of capturing logistics information in a logistics Query Web page:

  • The one that is smeared out is the target address; this is to insert my script into the target page. After success, an iframe with local address but the same domain name and target domain will be inserted into the web page.

result

The data can be returned to the local area after the request is successful.

For more details, please clickAjax cross domain technology summaryTo conduct in-depth study and research.

In fact, Xiaobian is also the front-end of the initial knowledge, and is still in the process of learning and exploring. I hope to learn and progress with you.