


Implement ajax cross-domain request based on iframe to obtain ajax data in web pages
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('<iframe src=' + mySrc + ' name="myIframe" id="getData"></frame>'); //向目标网页插入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: '/query?'+ orderId +'&id=1&valicode=&temp=' + Math.random(), method: 'GET', success: function(res) { console.log(res); //可以在此再调用子域的方法,向本地文件传输数据 }, error: function(err) { console.log('err: ', 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: './getOrderList.json',//本地数据存储的地方,偷懒直接写了个json文件,可以是数据库中的数据 method: 'GET', 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!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use
