javascript - 封装ajax
2023-09-11 14:14:38 时间
封装,使用有示例.
1 // 封装示例:
2 function ajax(url, method, params, done) {
3 var xhr = null;
4 method = method.toUpperCase();
5 xhr = window.XMLHttpRequest ? xhr = window.XMLHttpRequest : xhr = new ActiveXObject('Microsoft.XMLHTTP');
6
7 if (typeof params === 'object') {
8 var tempArr = [];
9 for (var key in params) {
10 var value = params[key];
11 tempArr.push(key + '=' + value);
12 }
13 params = tempArr.join('&');
14 }
15
16 // GET
17 if (method === 'GET') {
18 url += '?' + params;
19 }
20 xhr.open(method, url, false);
21
22 // POST
23 var data = null;
24 if (method === 'POST') {
25 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
26 data = params;
27 }
28
29 xhr.onreadystatechange = function () {
30 if (this.readyState !== 4 && this.status !== 200) return false;
31 ongone(this.responseText);
32 }
33 xhr.send(data);
34 }
35
36
37 // 调用示例:ajax('get','test.php',{id:123,},ongone)
38 ajax('GET', 'test.php', {}, ongone);
39
40 var ongone = function (res) {
41 console.log('1');
42 console.log('2');
43 console.log(res);
44 console.log('gone!');
45 }
相关文章
- 体验javascript之美第五课 五分钟彻底明白 匿名函数自执行和闭包
- JavaScript中的日期处理注意事项
- 第一百五十六节,封装库--JavaScript,延迟加载
- [Javascript] Broadcaster + Operator + Listener pattern -- 26. Share the Same Broadcaster Values Across Multiple Listeners
- [Javascript] Hide Properties from Showing Up in "for ... in" Loops in JavaScript
- [Javascript] Await a JavaScript Promise in an async Function with the await Operator
- [WASM] Call a JavaScript Function from WebAssembly
- [Javascript] Decorators in JavaScript
- 阅读《深入理解JavaScript定时机制》
- JavaScript 日期联动选择器
- javascript转换日期字符串为Date对象
- [Javascript] Filter out Duplicates from Flat JavaScript Array with array.filter / reduce / Set
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain (Object.setPrototypeOf())
- [Javascript] Natively Format JavaScript Dates and Times
- [Javascript] Wait for Multiple JavaScript Promises to Settle with Promise.allSettled()
- [ES2019] Represent Collision-free String Constants as Symbols in JavaScript
- [Javascript] Multiply Two Arrays over a Function in JavaScript
- [Javascript] Replicate JavaScript Constructor Inheritance with Simple Objects (OLOO)
- [Javascript] Understanding the .constructor property on JavaScript Objects
- [Javascript] Classify text into categories with machine learning in Natural
- [Javascript] Linting JavaScript with ESLint
- 6周学习计划,攻克JavaScript难关(React/Redux/ES6 etc.)
- 如何用JavaScript判断前端应用运行环境(移动平台还是桌面环境)
- 如何用JavaScript实现2+2=5?
- 【华为OD机试 2023】 查找重复代码(C++ Java JavaScript Python)
- 【华为OD机试 2023】士兵过河(C++ Java JavaScript Python)
- 【 华为OD机试 2023】信号发射和接收(C++ Java JavaScript Python)
- 《Javascript权威指南》十六学习笔记:BOM资源---BOM基本应用
- Web前端开发JavaScript基础