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

相关推荐
CSCN新手听安10 小时前
【linux】网络基础(三)TCP服务端网络版本计算器的优化,Json的使用,服务器守护进程化daemon,重谈OSI七层模型
linux·服务器·网络·c++·tcp/ip·json
bloglin9999911 小时前
Qwen3-32B报错Invalid json output:{“type“: “1“}For troubleshooting, visit
llm·json
Trouvaille ~12 小时前
【Linux】应用层协议设计实战(二):Jsoncpp序列化与完整实现
linux·运维·服务器·网络·c++·json·应用层
剩下了什么21 小时前
MySQL JSON_SET() 函数
数据库·mysql·json
梦帮科技1 天前
Node.js配置生成器CLI工具开发实战
前端·人工智能·windows·前端框架·node.js·json
数据知道1 天前
PostgreSQL实战:详解如何用Python优雅地从PG中存取处理JSON
python·postgresql·json
缘空如是2 天前
基础工具包之JSON 工厂类
java·json·json切换
墨痕诉清风2 天前
CVS文件转Json格式
json·python3·cvs
数研小生2 天前
1688商品列表API:高效触达批发电商海量商品数据的技术方案
大数据·python·算法·信息可视化·json
devmoon3 天前
快速了解兼容 Ethereum 的 JSON-RPC 接口
开发语言·网络·rpc·json·区块链·智能合约·polkadot