Home Web Front-end JS Tutorial Detailed explanation of several ajax request methods that may be encountered in actual combat

Detailed explanation of several ajax request methods that may be encountered in actual combat

Jan 01, 2018 pm 06:32 PM
ajax several kinds

This article mainly shares with you several ajax request methods that may be encountered in actual combat. The article introduces the ajax sample code in very detail, which has certain reference value for everyone. Friends who are interested in ajax follow Let’s take a look together.

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.

The ajax request method is as follows

1. Ordinary ajax, async means synchronous and asynchronous processing, after success, data will be returned Value, status request status, 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 
 } 
 
});
Copy after login

2. Sometimes the business logic 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 it is written in a callback method, it will be very complicated. It's lengthy. There are two solutions. First, let's 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 synchronization, ajax is executed one by one, so that 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{ 
    
  } 
 } 
});
Copy after login

(2) ES6 solution, use The then method of promise has the same effect as above. Ajax will be executed in order, and the subsequent ajax will get the return value of the previous ajax. When 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('请求失败'); 
}
Copy after login

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

Fourth, you will also encounter this kind of business logic. There are three asynchronous requests ajax1 ajax2 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 also needs to be new's promise

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

The above is all the content of this article, I hope it will be helpful to everyone's learning!

Related recommendations:

ajax cross-page submission form

ajax combined with Douban search results for paging complete code

Ajax implements partial refresh login interface with verification code

The above is the detailed content of Detailed explanation of several ajax request methods that may be encountered in actual combat. 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.

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.

What are the ajax versions? What are the ajax versions? Nov 22, 2023 pm 02:00 PM

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.

See all articles