JavaScript发起get请求的代码提取返回的json数据不要用第三方库
以下是JavaScript发起get请求并提取返回的json数据的示例代码:
const url = 'https://jsonplaceholder.typicode.com/todos/1'; // 请求的url
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest();
// 监听请求状态的变化
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) { // 请求已完成
if (xhr.status === 200) { // 请求成功
const response = JSON.parse(xhr.responseText); // 将返回的json数据解析为对象
console.log(response); // 输出返回的json数据
} else { // 请求失败
console.log('请求失败');
}
}
};
// 发起get请求
xhr.open('GET', url, true);
xhr.send();
注:以上示例代码仅供参考,实际应用中需要根据具体情况进行修改。
原文地址: https://www.cveoy.top/t/topic/0Bb 著作权归作者所有。请勿转载和采集!