This time I will show you how to use ajax requests in projects, and what are the precautions for using ajax requests in projects. The following is a practical case, let's take a look.
Preface
Recently I am working on a functional page for measuring the speed of a single node. The logic of the speed measurement is that when measuring the upload speed, the front end transmits 5m Send the data to the server, record the time of uploading and returning the data. When measuring the download speed, download 1m of data from the server, record the download and the time of successful download. Ajax synchronization is used for upload and download to avoid the problem of client bandwidth blocking, and Do this 3 times and take the average. During the development process, many detours were made due to the synchronization and asynchronous issues of Ajax, so I also compiled and summarized the business logic I encountered before.ajaxRequest method is as follows
1. Ordinary ajax, async means synchronous and asynchronous processing. After success, it will There is data return value, status request status, and xhr encapsulates the request header, but it should be noted that not all request header information can be obtained, such as center-length cannot be obtained$.ajax({ type: "GET", async: true, //异步执行 默认是true异步 url: url, dataType: "json", // jsonp: "callback", success: function(data, status, xhr){ console.log(data);//返回值 console.log(status);//状态 console.log(xhr);//obj console.log(xhr.getResponseHeader("Content-Type"));//application/octet-stream console.log(xhr.getResponseHeader("Center-Length"));//null } });2. The business logic sometimes encountered is like this. Request 2 depends on the return result of request 1, and request 3 depends on the return result of request 2. If written in callback mode, it will be very verbose. There are two solutions. Let’s first look at the ES5 solution (1) The ES5 solution is to use ajax to synchronize. The default ajax is asynchronous, that is, multiple requests are executed at the same time. After changing to synchronous, ajax is executed one by one. In this way, ajax2 can get the return result of ajax1
let res1 = "" let res2 = "" $.ajax({ type: 'get', async: false, //同步执行 默认是true异步 url: pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime(), dataType: 'json', success: function(res) { if(res.code == 0){ res1 = res.data.bandwidth[0] }else{ } } }); $.ajax({ type: 'get', async: false, //同步执行 默认是true异步 url: pars.domain + "/api.php?Action=xxx&date=2017-03-08&dom1111" + res1 + "&t=" + (new Date).getTime(), dataType: 'json', success: function(res) { if(res.code == 0){ res2 = res.data.bandwidth[0] }else{ } } });(2) ES6 solution, use the then method of promise, the effect is the same as above, ajax will be executed in order, and subsequent ajax will get The return value of the previous ajax, written like this, the code will look very smooth
let pro = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); console.log('请求pro成功'); }); //用then处理操作成功,catch处理操作异常 pro.then(requestA) .then(requestB) .then(requestC) .catch(requestError); function requestA(res){ console.log('上一步的结果:'+res); console.log('请求A成功'); let proA = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); }); return proA } function requestB(res){ console.log('上一步的结果:'+res); console.log('请求B成功'); let proB = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); }); return proB } function requestC(res){ console.log('上一步的结果:'+res); console.log('请求C成功'); let proC = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); }); return proC } function requestError(){ console.log('请求失败'); }3. jsonp cross-domain, dynamically add script tags to achieve cross-domain. Note that there is a callback that needs to be negotiated with the server
function switchEngineRoomAjax(api,statusChanged){ var api = api; var statusChanged = statusChanged; var url = api + "?method=setStatus" + "&status=" + statusChanged; $.ajax({ type: "GET", url: url, dataType: "jsonp", jsonp: "callback",// 这里的callback是给后端接收用的,前端通过动态添加script标签,完成回调 success: function(res){ if (res.code == 0) { console.log('更改状态 jsonp获取数据成功!'); } else{ } } }); };Fourth, you will also encounter this kind of business logic. There are three asynchronous requests of ajax1, ajax2, and ajax3. It is not necessarily which one returns the data first. After all requests are successful, a callback function is executed. It should be noted that a separate ajax is also The promise that needs to be new
ajax1:function(){ var promise = new Promise(function (resolve, reject) { var url = "/api.php?Action=xxx; $.get(url, function(res) { if (res.code == 0) { resolve('queryLog完成!'); } else{ } }, "json"); }); return promise }, ajax2: function(){ var promise = new Promise(function (resolve, reject) { var url = "/api.php?Action=xxx; $.get(url, function(res) { if (res.code == 0) { resolve('queryGroupNodeList完成!'); } else{ } }, "json"); }); return promise }, ajax3: function(){ var promise = new Promise(function (resolve, reject) { var url = "/api.php?Action=xxx; $.get(url, function(res) { if (res.code == 0) { resolve('queryGroupNodeMapList完成!'); } else{ } }, "json"); }); return promise }, initQuery: function(){ var mySelf = this; var promiseList = []; var ajax1Promise = mySelf.ajax1(); var ajax2Promise = mySelf.ajax2(); var ajax3Promise = mySelf.ajax3(); promiseList.push(ajax1Promise,ajax2Promise,ajax3Promise); var p1 = new Promise(function (resolve, reject) { console.log('创建1.2秒延时执行promise'); setTimeout(function () { resolve("1.2秒延时执行promise"); }, 1200); }); promiseList.push(p1) Promise.all(promiseList).then(function (result) { console.log('ajax全部执行完毕:' + JSON.stringify(result)); // ["Hello", "World"] mySelf.assembleTableData(); }); },
# I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website! Recommended reading:
jQuery+Ajax determines whether the entered verification code passes
How to make a smart search box with Ajax Prompt function
The above is the detailed content of How to use ajax request in project. For more information, please follow other related articles on the PHP Chinese website!

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.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.


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

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

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
