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

相关推荐
面朝大海,春不暖,花不开11 小时前
结构化数据格式解析:JSON 与 XML 的技术应用与实践
xml·json
PythonicCC14 小时前
Django核心知识点详解:JSON、AJAX、Cookie、Session与用户认证
ajax·django·json
-凌凌漆-16 小时前
【Qt】Qt QML json处理
开发语言·qt·json
racerun1 天前
UniApp中的pages.json 和 tabBar
uni-app·json
我命由我123452 天前
前端开发问题:SyntaxError: “undefined“ is not valid JSON
开发语言·前端·javascript·vue.js·json·ecmascript·js
Code季风2 天前
将 gRPC 服务注册到 Consul:从配置到服务发现的完整实践(上)
数据库·微服务·go·json·服务发现·consul
yjb.gz2 天前
Oracle函数JSON_TABLE使用
数据库·oracle·json
百锦再4 天前
.Net配置文件appsetting.json的几种读取方法
chrome·json·.net·依赖注入·appsetting·web.config
葬歌倾城5 天前
JSON的缩进格式方式和紧凑格式方式
c#·json
火车叨位去19496 天前
Java中的JSON序列化和反序列化
json