文章内容
2022/12/19 9:38:59,作 者: 黄兵
Javascript HTTP 请求
有几种方法可以在 JavaScript 中进行 HTTP 请求。一种方法是使用 XMLHttpRequest
对象,它在所有的现代浏览器中都可用。下面是一个使用 XMLHttpRequest
进行 GET 请求以获取一个 JSON 文件的例子:
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set the URL of the resource you want to retrieve
var url = "http://pdf-lib.org/data.json";
// Set up an event handler to be called when the request finishes
xhr.onload = function () {
// Check the status code
if (xhr.status === 200) {
// If the request was successful, get the data from the response
var data = JSON.parse(xhr.responseText);
// Do something with the data
}
};
// Open the request with the specified method (GET) and URL
xhr.open("GET", url);
// Send the request
xhr.send();
另一种在 JavaScript 中进行 HTTP 请求的方法是使用 fetch()
函数,该函数在现代浏览器中可用,对于旧的浏览器可以使用 polyfilled。fetch()
函数返回一个promise,该承诺可解析为一个 Response 对象,该对象包含对请求的响应。下面是一个使用 fetch()
进行 GET 请求的例子,以检索一个 JSON 文件:
// Set the URL of the resource you want to retrieve
var url = "http://pdf-lib.org/data.json";
// Call fetch with the URL of the resource you want to retrieve
fetch(url)
// When the request is complete, parse the response as JSON
.then(response => response.json())
// Do something with the data
.then(data => {
// Do something with the data
});
请注意,XMLHttpRequest
和 fetch()
都是异步的,这意味着事件处理程序或 then() 函数中的代码将不会被执行,直到请求完成。
总结
上面使用了两种方法实现 JavaScript 中实现 HTTP 请求,同时给出了相应代码,相对于 XMLHttpRequest, 我觉等 fetch() 更好一些,代码简洁。
当然上面只是我个人的习惯,如果有问题欢迎下面交流。
评论列表