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

相关推荐
Snowbowღ11 小时前
OpenAI / GPT-4o:Python 返回结构化 / JSON 输出
python·json·openai·api·gpt-4o·pydantic·结构化输出
林戈的IT生涯12 小时前
MySQL5.7中增加的JSON特性的处理方法JSON_EXTRACT和JSON_ARRAY_APPEND以及MYSQL中JSON操作的方法大全
json·mysql5.7·json特性·json_extract·mysql中json操作方法
敲代码不忘补水13 小时前
Python 项目实践:简单的计算器
开发语言·python·json·项目实践
亚林瓜子1 天前
Jackson注解屏蔽某些字段读取权限
spring·json·jackson
不惑_2 天前
最佳实践 · 如何高效索引MySQL JSON字段
java·mysql·json
天上掉下来个程小白2 天前
请求响应-05.请求-日期参数&JSON参数
spring boot·json
敲代码不忘补水2 天前
Python Pickle 与 JSON 序列化详解:存储、反序列化与对比
开发语言·python·json
jackletter3 天前
c#:System.Text.Json 的使用四(如何忽略[JsonPropertyName])
c#·json·序列化
A 八方3 天前
Python JSON
开发语言·python·json
小故渊3 天前
JSON对象
运维·服务器·json