AJAX – 服务器响应

当通过 AJAX 向服务器发送请求时,服务器会返回响应,AJAX 可以处理这个响应并在网页上更新内容。服务器响应的内容可以是 文本JSONXML 等格式。

下面介绍如何处理不同类型的服务器响应。


1. 响应的状态码

每个服务器响应都带有一个状态码,表示请求的结果。最常见的状态码如下:

状态码描述
200请求成功,服务器返回响应数据
404请求的资源未找到
500服务器内部错误
403禁止访问,权限不足
401未授权,需要身份验证

在 AJAX 请求中,使用 xhr.status 获取服务器响应的状态码。


2. 使用 XMLHttpRequest 获取服务器响应

获取文本数据

如果服务器返回的是普通文本数据,可以通过 xhr.responseText 获取响应内容。

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("服务器返回的文本数据:", xhr.responseText);
    }
};

xhr.send();

获取 JSON 数据

如果服务器返回 JSON 格式的数据,可以通过 xhr.responseText 获取字符串,然后使用 JSON.parse() 将其解析为 JavaScript 对象。

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var data = JSON.parse(xhr.responseText);
        console.log("服务器返回的 JSON 数据:", data);
    }
};

xhr.send();


3. 使用 Fetch API 获取服务器响应

fetch() 是现代浏览器推荐的 AJAX 请求方法,简化了许多操作,支持更丰富的响应处理。

获取文本数据

fetch("data.txt")
    .then(response => response.text())  // 将响应转化为文本
    .then(data => console.log("服务器返回的文本数据:", data))
    .catch(error => console.error("请求失败:", error));

获取 JSON 数据

fetch("data.json")
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP 错误, 状态码: " + response.status);
        }
        return response.json();  // 将响应转化为 JSON 对象
    })
    .then(data => console.log("服务器返回的 JSON 数据:", data))
    .catch(error => console.error("请求失败:", error));

获取其他类型的响应(如 Blob, ArrayBuffer 等)

fetch() 还支持处理 Blob(例如图片文件)和 ArrayBuffer(二进制数据)等响应类型:

fetch("image.jpg")
    .then(response => response.blob())  // 获取图片二进制数据
    .then(imageBlob => {
        const imageURL = URL.createObjectURL(imageBlob);
        document.querySelector("img").src = imageURL;
    })
    .catch(error => console.error("请求失败:", error));


4. 处理服务器错误

在实际应用中,AJAX 请求可能会遇到不同的错误。通过监听错误事件或使用 catch() 处理这些错误。

使用 XMLHttpRequest 错误处理

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);

xhr.onerror = function() {
    console.error("请求出错!");
};

xhr.ontimeout = function() {
    console.error("请求超时!");
};

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("服务器返回的文本数据:", xhr.responseText);
    } else if (xhr.readyState === 4 && xhr.status !== 200) {
        console.error("请求失败,状态码:", xhr.status);
    }
};

xhr.timeout = 5000; // 设置超时时间为 5 秒
xhr.send();

使用 Fetch API 错误处理

fetch("data.txt")
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP 错误, 状态码: " + response.status);
        }
        return response.text();
    })
    .then(data => console.log("服务器返回的文本数据:", data))
    .catch(error => console.error("请求失败:", error));


5. 处理不同类型的响应

服务器可以返回多种类型的响应数据,常见的响应类型包括:

文本响应

如果服务器返回纯文本数据,可以通过 responseText 获取。

JSON 响应

如果服务器返回 JSON 数据,需要使用 JSON.parse()response.json() 将其转化为 JavaScript 对象。

XML 响应

如果服务器返回 XML 数据,可以使用 responseXML 获取。

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);

xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var xmlDoc = xhr.responseXML;
        console.log("服务器返回的 XML 数据:", xmlDoc);
    }
};

xhr.send();


6. 服务器响应时的常用属性

  • responseText: 服务器返回的文本数据(适用于文本或 JSON 格式的响应)。
  • responseXML: 服务器返回的 XML 数据(适用于 XML 格式的响应)。
  • status: 服务器返回的 HTTP 状态码(例如,200 表示成功,404 表示未找到资源)。
  • statusText: 服务器返回的状态信息(例如 “OK”、”Not Found”)。
  • readyState: 请求的当前状态(0-4)。
  • getResponseHeader(header): 获取指定的响应头信息。

总结

  • XMLHttpRequest:通过 xhr.responseTextxhr.responseXML 获取响应数据。
  • fetch():通过 .text().json().blob() 等方法处理不同类型的响应。
  • 需要注意 错误处理服务器状态码
  • 推荐使用 fetch(),它简洁、易于使用,且支持 Promise。

🚀 如果你希望你的代码更简洁且易于维护,推荐使用 fetch() 处理响应!