JavaScript 中的网络请求方式通常是通过浏览器提供的 XMLHttpRequest
对象或者 Fetch API
来实现的。这些请求方式用于从服务器获取数据或向服务器发送数据。以下是不同请求方式的应用示例:
1. GET 请求:
GET 请求用于从服务器获取数据。它通常用于获取资源,不会对服务器上的数据进行修改。
使用 XMLHttpRequest
:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
console.log(responseData);
}
};
xhr.send();
使用 Fetch API
:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
2. POST 请求:
POST 请求用于向服务器提交数据。它通常用于创建资源或在服务器上执行操作。
使用 XMLHttpRequest
:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/create', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 201) {
const responseData = JSON.parse(xhr.responseText);
console.log(responseData);
}
};
const requestData = { name: 'Alice', age: 25 };
xhr.send(JSON.stringify(requestData));
使用 Fetch API
:
fetch('https://api.example.com/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Alice', age: 25 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
3. 其他请求方式(PUT、DELETE 等):
类似地,你可以使用相应的请求方式来执行其他操作,例如使用 PUT 请求来更新资源,使用 DELETE 请求来删除资源。
// 使用 PUT 请求更新资源
fetch('https://api.example.com/update', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: 1, name: 'Updated Name' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// 使用 DELETE 请求删除资源
fetch('https://api.example.com/delete/1', {
method: 'DELETE'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
这些示例展示了使用不同请求方式从服务器获取数据或向服务器发送数据的方法。在现代开发中,通常推荐使用 Fetch API
,它提供了更简洁、灵活和现代化的方式来处理网络请求。