// 使用 XMLHttpRequest 进行简单的 GET 请求
function sendGetRequest(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功,调用回调函数并传递响应文本
callback(xhr.responseText);
}
};
xhr.open("GET", url, true);
xhr.send();
}
// 示例:发送 GET 请求并打印响应
sendGetRequest('https://jsonplaceholder.typicode.com/posts/1', function(response) {
console.log('Response:', response);
});
// 使用 Fetch API 进行 GET 请求
async function fetchGetData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log('Fetched Data:', data);
} catch (error) {
console.error('Fetch Error:', error);
}
}
// 示例:使用 Fetch API 发送 GET 请求
fetchGetData('https://jsonplaceholder.typicode.com/posts/1');
// 使用 Fetch API 进行 POST 请求
async function fetchPostData(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const responseData = await response.json();
console.log('Posted Data:', responseData);
} catch (error) {
console.error('Fetch Error:', error);
}
}
// 示例:使用 Fetch API 发送 POST 请求
const postData = { title: 'foo', body: 'bar', userId: 1 };
fetchPostData('https://jsonplaceholder.typicode.com/posts', postData);
XMLHttpRequest:
sendGetRequest
函数展示了如何使用 XMLHttpRequest
对象发送一个简单的 GET 请求。Fetch API:
fetchGetData
函数展示了如何使用现代的 Fetch API 发送 GET 请求,并处理响应数据。fetchPostData
函数展示了如何使用 Fetch API 发送 POST 请求,并传递 JSON 数据。上一篇:js switch语法
下一篇:js click方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站