Home >Web Front-end >JS Tutorial >Implement ajax cross-domain request based on iframe to obtain ajax data in web pages

Implement ajax cross-domain request based on iframe to obtain ajax data in web pages

亚连
亚连Original
2018-05-24 11:19:592436browse

This article mainly introduces the implementation of ajax cross-domain request based on iframe and obtaining the ajax data in the web page. How to use the interface exposed by the ajax request on the web page to crawl the web page data? Friends in need can refer to

As we all know, it is not possible to send ajax requests in different domains. The browser will report the following error:

At the same time, cross-domain communication is not possible in embedded iframes, which means that iframes in different domains cannot read data from each other (of course, data can be passed from the parent window to the child iframe using hash changes, but it does not 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’s how to solve this problem.

In fact, the key to the problem is that when the browser parses the ajax request address, it will compare it with the address of the current web page. If it is cross-domain, it will be disabled and an error will be reported. So if we let the ajax address parsed by the browser be the same as the parsed address of the current web page, won't the browser prohibit our request?

So how does the browser parse the url?

First, when the browser accesses a domain name, it will query the local DNS cache to see if there is an IP address corresponding to this URL. If so, it will directly obtain the IP address from the local and then access it. If not, the browser will A DNS request will be sent to the DNS server to obtain the IP address corresponding to the domain name and then stored in the local cache and then accessed.

So because 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:\Windows\System32\drivers\etc
There is a hosts file under this folder. If you have changed hosts to go to Google, you should be familiar with this. Add it to the hosts file. Enter a piece of code like this:

127.0.0.1 a.Destination URL.com

In this way, your visit to a.Destination URL.com will be the same as It is the same as accessing localhost. The purpose of this is to facilitate the establishment of local services. There will be no cross-domain problems between the local services and the target domain name. In this way, the iframe tag can be implanted locally in the target web page. method, initiate a cross-domain request to the target domain and obtain the data of the target domain.

Upload the code directly (using jQuery)

Script code, insert directly into the html code in the parent domain

var mySrc = "http://a.目标网址.com:9000/myIframe.html";

document.domain = "目标网址.com";  //关键代码,将域提升到根域

$("body").append(&#39;<iframe src=&#39; + mySrc + &#39; name="myIframe" id="getData"></frame>&#39;);  //向目标网页插入iframe

var interval;

function start() {
 $("#getData").attr({"src": mySrc});
 interval = setInterval(function() {
  window.myIframe.run(getLogitic); //向子域传入回调函数  
 },10000)
}

function stop() {
 clearInterval(interval);
}

function getLogitic(orderId) {
 $.ajax({
  url: &#39;/query?&#39;+ orderId +&#39;&id=1&valicode=&temp=&#39; + Math.random(),
  method: &#39;GET&#39;,
  success: function(res) {
   console.log(res);    //可以在此再调用子域的方法,向本地文件传输数据
  },
  error: function(err) {
   console.log(&#39;err: &#39;, err);
  }
 })
}

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 = "目标网址.com"; //关键代码,将子域提升到根域
  var int;
  function run(callback) {
  //此请求用于向本地请求数据,然后根据本地的数据,利用父域传过来的回调函数向目标域发起请求,得到目标域的数据 
   $.ajax({
    url: &#39;./getOrderList.json&#39;,//本地数据存储的地方,偷懒直接写了个json文件,可以是数据库中的数据
    method: &#39;GET&#39;,
    success: function(res) {
     var data = res.list;
     int = setInterval(function(){
      callback(data[0]); //执行父域传入的回调函数
      data.shift();
      if (data.length === 0) clearInterval(int);
     }, 1000);
    },
    error: function(err) {
     console.log(err)
    }
   })
  }
 </script>
</body>
</html>

Note:

Only by promoting the iframe to the root domain can it communicate with the parent window. The document.domain command can only promote the current domain to the current root domain. This is also the reason why the local hosts file must be modified. This is a solution to cross-border conflicts. The root of the domain problem.
Before crawling the target web page data, you must first look at the way the target web page sends an ajax request, get the requested api, insert the script through the console of the target web page, and then run it to get the data you want to get. After passing and local request method, sent to the local.
The following is the process of grabbing logistics information from a logistics query webpage:

  • The blackout is the target URL; this is to insert my URL into the target webpage After the script is successful, an iframe with a local address but the same domain name and target domain will be inserted into the web page.

Result

These data can be transferred back to the local when the request is successful.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

ajax quickly solves the problem of parameters that are too long and cannot be submitted successfully

Use loading images to solve the problem of Ajax data loading The page appears temporarily blank

Quick solution to the problem that the Ajax form page will still refresh after submitting the form

The above is the detailed content of Implement ajax cross-domain request based on iframe to obtain ajax data in web pages. For more information, please follow other related articles on the PHP Chinese website!

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