Ajax 学习笔记
这几天在学习 node.js,看到 Ajax 的部分内容比较零散,很难记忆,但是 Ajax 又是相当重要的知识,实际开发中也常常会用到,所以写个笔记来整理一下。
请求参数的格式
在请求头中指定 Content-Type 属性的值
name=zhangsan&age=20&sex=男
2. application/json
{name: 'zhangsan', age: '20', sex: '男'}
注意:get 请求是不能提交 json 对象数据格式的,传统网站的表单提交也是不支持 json 对象数据格式的。
Ajax 状态码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <script> var xhr = new XMLHttpRequest(); console.log(xhr.readyState); xhr.open("get", "http://localhost:3000/readystate"); console.log(xhr.readyState);
xhr.onreadystatechange = function () { console.log(xhr.readyState);
if (xhr.readyState == 4) { console.log(xhr.resposeText); } };
xhr.send(); </script>
|
获取服务器端的响应
两种获取方式的区别
| 区别描述 |
onload 事件 |
onreadystatechange 事件 |
| 是否兼容 IE 低版本 |
不兼容 |
兼容 |
| 是否需要判断 Ajax 状态码 |
不需要 |
需要 |
| 被调用次数 |
一次 |
多次 |
推荐使用 onload
IE 低版本浏览器缓存问题
两次请求相同的地址时,第二次请求并不会真正发送出去,而是直接从缓存中取上一次的响应结果。
解决方法:在发送请求的地址上用?拼接一个随机参数,使得每次请求的地址不相同。
Ajax 封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| function ajax(options) { var defaults = { type: "get", url: "", data: {}, header: { "Content-Type": "application/x-www-form-urlencoded" }, success: function () {}, error: function () {}, };
Object.assign(defatuls, options);
var xhr = new XMLHttpRequest(); var params = ""; for (var attr in defaults.data) { params += attr + "=" + defaults.data[attr] + "&"; } params = params.substr(0, params.length - 1);
if (defaults.type == "get") { defaults.url = defaults.url + "?" + params; } xhr.open(defaults.type, defaults.url); if (defaults.type == "post") { var contentType = defaults.header["Content-Type"]; xhr.setRequsetHeader("Content-Type", contentType); if (contentType == "application/json") { xhr.send(JSON.stringify(defaults.data)); } else { xhr.send(params); } } else { xhr.send(); }
xhr.onload = function () { if (xhr.status == 200) { defaults.success(xhr.responseText, xhr); } else { defaults.error(xhr.responseText, xhr); } }; }
ajax({ type: "get", url: "http://localhost:3000/first", data: { name: "zhangsan", age: 20, }, header: { "Content-Type": "application/x-www-form-urlencoded", }, success: function (data, xhr) { console.log(data); }, error: function (data, xhr) { console.log(data); }, });
|