AJAX 出现以前,如何发请求?

用 form 可以发请求,但是会刷新页面或新开页面。
用 a 可以发 get 请求,但是也会刷新页面或新开页面。
用 img 可以发 get 请求,但是只能以图片的形式展示。
用 link 可以发 get 请求,但是只能以 CSS、favicon 的形式展示。
用 script 可以发 get 请求,但是只能以脚本的形式运行。

有没有什么方式可以实现:

  1. get、post、put、delete 请求都行。
  2. 想以什么形式展示就可以以什么形式展示。

微软的突破

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 语法的字符串。

  1. const xhr = new XMLHttpRequest();
  2. xhr.onreadystatechange = () => {
  3. if (xhr.readyState === 4) {
  4. if (xhr.status >= 200 && xhr.status <= 300) {
  5. console.log("success");
  6. let parser = new DOMParser();
  7. let xmlDor = parser.parseFromString(xhr.responseText, "text/xml");
  8. let title = xmlDor.getElementsByTagName("to")[0].textContent;
  9. console.log(title);
  10. } else if (xhr.status >= 400) {
  11. console.log("failed");
  12. }
  13. }
  14. };
  15. xhr.open("GET", "/xxx");
  16. xhr.send();

使用这这种方法很麻烦,要新建一个 DOMParser 对象去解析 xml。所以现在都是使用 JSON 来代替 XML。

AJAX(JSON)

  1. const xhr = new XMLHttpRequest();
  2. xhr.onreadystatechange = () => {
  3. if (xhr.readyState === 4) {
  4. if (xhr.status >= 200 && xhr.status <= 300) {
  5. console.log("success");
  6. const obj = JSON.parse(xhr.responseText);
  7. console.log(obj.note.to);
  8. } else if (xhr.status >= 4000) {
  9. console.log("failed");
  10. }
  11. }
  12. };
  13. xhr.open("GET", "/xxx");
  14. 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”]
  1. JSON 没有抄袭 function 和 undefined。
  2. JSON 的字符串首尾必须是双引号。

参考:

[1] Ajax知识体系大梳理
[2] XMLHttpRequest