Front and back end data interaction (III) -- Ajax encapsulation and call

stupid 2021-10-14 01:33:32
end data interaction iii ajax

There are many frameworks that have ajax encapsulation , Just call it when you need it , such as jquery Is the most commonly used . Why do we need to learn ajax The packaging? ? First, strengthen our understanding of ajax The understanding of , Second, if it's just because ajax The request needs to be introduced into the framework , We can encapsulate one by ourselves , This eliminates the need to introduce redundant frameworks .

One 、 Packaging considerations

Encapsulation is to make the same parts common , Save resources , Improve code reusability , Work efficiency is also high , Therefore, different parameter event types need to be passed in through the call , I need to pay attention to :

1.1、 The ginseng

send out ajax When asked , The main parameters are :

  • request url
  • Request type
  • Request parameters
  • Successful callback
  • Failed callback
  • Timeout time

The above six parameters must be set to be dynamically passed in , Easy to control arbitrary ajax request . The timeout can be set uniformly , If it is used as a parameter, it is more convenient to control the timeout of any request .

1.2、 Request types are processed separately

The request types are get and post Two kinds of ,get When a type passes a value , Data follow url After the address ,post Carry in the request body when transmitting value , You also need to set the request data type . Therefore, we need to judge and deal with them separately .

if(type == 'GET'){ 'GET' , url+'?'+strData , true )
xhr.send( strData )

1.3、 Request timeout processing

When the network service or interface is abnormal , The request was sent without response , The page will not respond , A global timeout is required , When the time out has not returned , Auto end request , Return exception .

The syntax is as follows :

// Set the time to 2s
xhr.timeout = 2000 ;
// Timeout callback
xhr.ontimeout = function(){
console.log(' Network anomalies , Try again later ')

1.4、 Error handling

Network interruption , When the request cannot be sent to the server , Request failures need to be handled . Use onerror Event handling .

The syntax is as follows :

xhr.onerror = function(){
console.log(" Network anomalies , Please check the network ")

Two 、 encapsulation ajax Code

according to ajax Request flow , The encapsulation code is as follows : Easy to use later , Recommended collection .

function ajax(option) {
// method, url, data, timeout, success, error
var xhr;
var str = data2str(;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
if (option.type.toLowerCase() === 'post') {, option.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else if (option.type.toLowerCase() === 'get') {, option.url + '?' + str, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr === 304) {
}else {
if (option.timeout) {
var timer = setTimeout(function () {
}, option.timeout)
// Converts an object to a string for transmission
function data2str(data) {
var res = [];
data.t = new Date().getTime();
for (var key in data) {
res.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
return res.join('&');

The calling code is as follows :

// Request data
console.log(' Successfully returns ',res.response)
error: err => {
console.log(' error message ',err)

Link to the original text :


  1. PaddlePaddle:在 Serverless 架构上十几行代码实现 OCR 能力
  2. JavaScript数组 几个常用方法
  3. 暢談this的四種綁定方式
  4. 2021最新Vue面试必胜宝典,大厂面试题解析!
  5. Quatre façons de lier ceci
  6. Préparation au développement de l'extension tagdown
  7. Intervieweur: Parlez - moi des flotteurs CSS
  8. Packaging the View Component Library with rollup
  9. Comment un composant enfant modifie les valeurs passées par le composant parent
  10. Résumé de l'API Express
  11. Optimisation de la structure du Code if else dans le projet
  12. Fonction magique pour résoudre le problème de la fonction maybe - - fonction either
  13. 新手学前端的方法是什么 自学前端该怎么规划
  14. 云原生体系下 Serverless 弹性探索与实践
  15. 如何全方位打造安全高效的HTTPS站点(一)
  16. "Liu Jing dit che 丨 point de vue" est - ce que Custom Road est un MpV digne de la terre?
  17. 从理念到LRU算法实现,起底未来React异步开发方式
  18. Compared with Volvo XC60, Lingke 09 goes out of the spa platform. What would you choose, regardless of the brand?
  19. PaddlePaddle:在 Serverless 架构上十几行代码实现 OCR 能力
  20. 云原生体系下 Serverless 弹性探索与实践
  21. 初学者怎么学Web前端?
  22. react
  23. PaddlePaddle:在 Serverless 架构上十几行代码实现 OCR 能力
  24. JavaScript数组 几个常用方法
  25. Angular 依赖注入 - 全面解析
  26. html_day02
  27. 那些年我们前端面试中经常被问到的题!
  28. The starting price of Ducati multistada V2 in North America is less than 100000 yuan
  29. Hls.js 使用文檔
  30. Hls.js travailler avec des documents
  31. Problèmes liés à la précision JS
  32. Copie une partie des propriétés d'un objet à un autre objet
  33. Multiplexage de modules en vuex
  34. Développement multilingue Android, questions d'entrevue pour le développement de logiciels Android
  35. Chen lushai and her best friend Wang Meng play video, fearless of the pressure of public opinion, and in a good mood to dance in a bare back
  36. # Sass速通(四):继承、混合与函数
  37. Vidéo de développement de combat Android, questions d'entrevue rxjava
  38. Bugatti Chiron maintenance cost exposure! One piece for one car, burn money endlessly
  39. android应用开发基础答案,深入理解Nginx
  40. 做了三年前端,你才知道10分钟就能实现一个PC版魔方游戏
  41. Html + CSS + JS implémentation ️ Responsive Lucky Turnover ️ [with full source Sharing]
  42. Ren Jialun, who married young, was in a mess. Now she feels that it is a blessing in disguise
  43. 达梦数据库使用disql生成html格式的巡检报告
  44. React render phase parsing II - beginwork process
  45. Tableau linéaire de la structure des données (dessin à la main)
  46. In 2022, what are the highlights and popular elements in skirts to make skirts more elegant and gentle?
  47. JQuery installation
  48. Exemple de développement Android, dernière compilation de questions d'entrevue Android
  49. Differences and relations between JDK, JRE and JVM, nginx architecture diagram
  50. 【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)
  51. 【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)
  52. Questions d'entrevue pour les ingénieurs en développement Android, Android Foundation 72 questions
  53. It's kind of Cadillac CT6 to have a Mercedes Benz S-class captain and a 10At entry-level configuration, falling to less than 300000
  54. H6 meets the strong enemy again! The car body has a Cayenne visual sense, breaking 8.8 seconds, and the top configuration is less than 130000
  55. How nginx supports HTTPS and Linux kernel video tutorial
  56. Le martyr se réjouit de sa vieillesse Audi R8 V10 performance Rwd
  57. import 方式隨意互轉,感受 babel 插件的威力
  58. Le mode d'importation peut se déplacer librement pour sentir la puissance du plug - in Babel
  59. Pas de héros en termes de ventes!Du point de vue de la force du produit, la nouvelle version ax7 Mach est plus forte que H6
  60. The vue3 + TS project introduces vant as needed