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

May 24, 2018 am 11:19 AM
ajax iframe ask

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

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>
Copy after login

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 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Monitor iframe scrolling behavior Monitor iframe scrolling behavior Feb 18, 2024 pm 08:40 PM

How to monitor the scrolling of an iframe requires specific code examples. When we use the iframe tag to embed other web pages in a web page, sometimes we need to perform some specific operations on the content in the iframe. One of the common needs is to listen for the scroll event of the iframe so that the corresponding code can be executed when the scroll occurs. The following will introduce how to use JavaScript to monitor the scrolling of an iframe, and provide specific code examples for reference. Get the iframe element First, we need

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles