Asynchronous JavaScript 和 AJAX

学习如何在异步JavaScript中使用JSON,特别是在AJAX(Asynchronous JavaScript and XML)调用中如何发送和接收JSON数据


在异步JavaScript中,AJAX(Asynchronous JavaScript and XML)是一种技术,它允许你在不刷新页面的情况下与服务器进行数据交换和更新部分网页内容。尽管AJAX的名字中包含XML,但现在更常用的是JSON(JavaScript Object Notation)数据格式,因为它更轻量,且易于与JavaScript交互。

下面是如何在AJAX调用中发送和接收JSON数据的步骤:

使用`XMLHttpRequest`发送和接收JSON

**发送JSON数据到服务器**:

```javascript

// 创建一个新的 XMLHttpRequest 对象

var xhr = new XMLHttpRequest();

// 配置请求类型、URL 以及是否异步处理

xhr.open('POST', 'your-endpoint-url', true);

// 设置请求头,告诉服务器消息主体是 JSON

xhr.setRequestHeader('Content-Type', 'application/json');

// 设置响应类型为 JSON

xhr.responseType = 'json';

// 设置一个函数来处理来自服务器的响应

xhr.onload = function () {

if (xhr.status >= 200 && xhr.status < 300) {

// 请求成功,处理响应数据

console.log('Success:', xhr.response);

} else {

// 请求失败,处理错误

console.error('The request failed!');

}

};

// 准备发送的 JSON 数据

var data = JSON.stringify({ name: 'John', age: 30 });

// 发送请求,并携带 JSON 数据

xhr.send(data);

```

**从服务器接收JSON数据**:

```javascript

// 创建 XMLHttpRequest 对象

var xhr = new XMLHttpRequest();

// 配置 GET 请求

xhr.open('GET', 'your-endpoint-url', true);

// 设置响应类型为 JSON

xhr.responseType = 'json';

// 设置响应数据处理函数

xhr.onload = function () {

if (xhr.status >= 200 && xhr.status < 300) {

// 请求成功,处理响应数据

console.log('Success:', xhr.response);

} else {

// 请求失败,处理错误

console.error('The request failed!');

}

};

// 发送请求

xhr.send();

```

使用`fetch` API发送和接收JSON

`fetch` API提供了一种更现代、更强大且更灵活的方式来发起网络请求。它返回一个`Promise`,使得它可以更容易地与异步代码一起工作。

**发送JSON数据到服务器**:

```javascript

// 准备发送的 JSON 数据

var data = { name: 'John', age: 30 };

// 使用 fetch 发送 POST 请求

fetch('your-endpoint-url', {

method: 'POST', // 请求方法

headers: {

'Content-Type': 'application/json', // 指定发送到服务器的数据类型

},

body: JSON.stringify(data), // 将 JavaScript 对象转换为字符串

})

.then(response => {

if (!response.ok) {

throw new Error('Network response was not ok ' + response.statusText);

}

return response.json(); // 解析 JSON 数据

})

.then(data => {

console.log('Success:', data);

})

.catch(error => {

console.error('There has been a problem with your fetch operation:', error);

});

```

**从服务器接收JSON数据**:

```javascript

// 使用 fetch 发送 GET 请求

fetch('your-endpoint-url')

.then(response => {

if (!response.ok) {

throw new Error('Network response was not ok ' + response.statusText);

}

return response.json(); // 解析 JSON 数据

})

.then(data => {

console.log('Success:', data);

})

.catch(error => {

console.error('There has been a problem with your fetch operation:', error);

});

```

使用`fetch`时,你可以链式调用`.then()`来处理Promise,这使得代码更加清晰和易于管理。同时,`fetch`也支持`async/await`语法,这可以让异步代码看起来更像同步代码。

使用`async/await`与`fetch`结合

```javascript

// 定义一个异步函数

async function fetchData() {

try {

// 等待 fetch 请求并获取响应

const response = await fetch('your-endpoint-url');

if (!response.ok) {

throw new Error('Network response was not ok');

}

// 等待响应解析为 JSON

const data = await response.json();

console.log('Success:', data);

} catch (error) {

console.error('There has been a problem with your fetch operation:', error);

}

}

// 调用异步函数

fetchData();

```

在这个例子中,`async`关键字用于声明一个异步函数,在该函数内部,你可以使用`await`关键字等待一个Promise解决。这种方式可以让你以一种更直观的方式编写异步代码。

相关推荐
陈涛5752 天前
5个最好用的 JSON 工具推荐:让数据处理变得简单高效
json
bkspiderx2 天前
pb2json.hpp 文档:Protobuf 与 JSON 通用转换工具类
json·protobuf·protobuf与json转换
万粉变现经纪人3 天前
何解决PyCharm中pip install安装Python报错ModuleNotFoundError: No module named ‘json’问题
python·pycharm·json·beautifulsoup·scikit-learn·matplotlib·pip
晨欣4 天前
orjson 与 json:实战对比与选型指南(含示例)(GPT-5 回答)
gpt·json
Pi_Qiu_4 天前
Python初学者笔记第二十二期 -- (JSON数据解析)
笔记·python·json
mon_star°4 天前
有趣的 npm 库 · json-server
前端·npm·json
ID_180079054734 天前
淘宝拍立淘按图搜索API接口功能详细说明
大数据·python·json·图搜索算法
cypking5 天前
vue excel转json功能 xlsx
vue.js·json·excel
我又来搬代码了5 天前
【Android】【bug】Json解析错误Expected BEGIN_OBJECT but was STRING...
android·json·bug
山里幽默的程序员6 天前
如何使用Postman无障碍导入JSON文件?详细步骤&工具对照
测试工具·json·postman