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解决。这种方式可以让你以一种更直观的方式编写异步代码。

相关推荐
远方16091 天前
16-Oracle 23 ai-JSON-Relational Duality-知识准备
数据库·oracle·json
sc写算法1 天前
基于nlohmann/json 实现 从C++对象转换成JSON数据格式
开发语言·c++·json
酷爱码1 天前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
不惑_2 天前
用 PyQt5 打造一个可视化 JSON 数据解析工具
开发语言·qt·json
漫游者Nova2 天前
PDF转Markdown/JSON软件MinerU最新1.3.12版整合包下载
pdf·json·markdown·mineru
snow@li2 天前
vue3+ts+vite:详细、完整的 tsconfig.json 示例 / 常见配置项及其用途
json·tsconfig.json
南郁2 天前
007-nlohmann/json 项目应用-C++开源库108杰
c++·开源·json·nlohmann·现代c++·d2school·108杰
紫乾20143 天前
idea json生成实体类
java·json·intellij-idea
愿你天黑有灯下雨有伞4 天前
MyBatis-Plus LambdaQuery 高级用法:JSON 路径查询与条件拼接的全场景解析
mysql·json·mybatis
wtsolutions4 天前
JSON to Excel 3.0.0 版本发布 - 从Excel插件到Web应用的转变
json·excel·json-to-excel·wtsolutions