AJAX 出现以前,如何发请求?
用 form 可以发请求,但是会刷新页面或新开页面。
用 a 可以发 get 请求,但是也会刷新页面或新开页面。
用 img 可以发 get 请求,但是只能以图片的形式展示。
用 link 可以发 get 请求,但是只能以 CSS、favicon 的形式展示。
用 script 可以发 get 请求,但是只能以脚本的形式运行。
有没有什么方式可以实现:
- get、post、put、delete 请求都行。
- 想以什么形式展示就可以以什么形式展示。
微软的突破
IE 5 率先在 JS 中引入 ActiveX 对象(API),使得 JS 可以直接发起 HTTP 请求。
随后 Mozilla、 Safari、 Opera 也跟进(抄袭)了,取名 XMLHttpRequest,并被纳入 W3C 规范。
AJAX 是什么
ajax 全称:Asynchronous Javascript And Xml(异步的 javascript 和 xml 技术),用于网页向服务器发送请求的一种技术。
Jesse James Garrett(人名) 讲如下技术取名叫做 AJAX:
- 使用 XMLHttpRequest 发请求。
- 服务器返回 xml 格式的字符串(现在前端已经不用 xml 转而使用 json)。
- js 解析 XML,并局部更新页面。
AJAX(xml)
使用 ajax 返回符合 xml 语法的字符串。
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status <= 300) {
console.log("success");
let parser = new DOMParser();
let xmlDor = parser.parseFromString(xhr.responseText, "text/xml");
let title = xmlDor.getElementsByTagName("to")[0].textContent;
console.log(title);
} else if (xhr.status >= 400) {
console.log("failed");
}
}
};
xhr.open("GET", "/xxx");
xhr.send();
使用这这种方法很麻烦,要新建一个 DOMParser 对象去解析 xml。所以现在都是使用 JSON 来代替 XML。
AJAX(JSON)
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status <= 300) {
console.log("success");
const obj = JSON.parse(xhr.responseText);
console.log(obj.note.to);
} else if (xhr.status >= 4000) {
console.log("failed");
}
}
};
xhr.open("GET", "/xxx");
xhr.send();
直接使用 JSON.parse 解析符合 JSON语法的字符串。
json 是什么
JSON(javascript Object Notation)是一种轻量级的数据交换格式,在 AJAX 中主要用于代替 xml。
json 和 javascript 的区别
javascript | json |
---|---|
undefined | 没有 |
var a = {} | 没有 |
function | 没有 |
null | null |
{name: ‘cxx’} | {“name”: “cxx”} |
[‘a’, ‘b’] | [“a”, “b”] |
- JSON 没有抄袭 function 和 undefined。
- JSON 的字符串首尾必须是双引号。
参考:
[1] Ajax知识体系大梳理
[2] XMLHttpRequest