js如何获取网页php网页里面的api JSON数据
可以使用JavaScript中的AJAX技术来获取PHP网页里面的API JSON数据。
以下是一个简单的示例:
- 创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
- 设置请求的方法和URL
xhr.open('GET', 'api.php', true);
- 设置请求头信息
xhr.setRequestHeader('Content-type', 'application/json');
- 发送请求
xhr.send();
- 监听请求状态变化
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// 处理返回的JSON数据
}
};
在上述代码中,xhr.onreadystatechange函数会在请求状态变化时被调用。当请求状态为4(请求已完成)且状态码为200(请求成功)时,可以通过xhr.responseText获取到返回的JSON数据。需要注意的是,返回的数据需要使用JSON.parse()方法进行解析
原文地址: https://www.cveoy.top/t/topic/g1L0 著作权归作者所有。请勿转载和采集!