可以使用 JavaScript 的 XMLHttpRequest 对象来获取 127.0.0.1/lib/index.php 的返回内容。
这是一个示例函数:
function getContent(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
使用方式如下:
getContent('http://127.0.0.1/lib/index.php')
.then(response => {
// 处理获取到的内容
console.log(response);
})
.catch(error => {
// 处理错误
console.error(error);
});
注意:如果使用的是跨域资源,则需要在服务器端设置 CORS(跨域资源共享)相关的响应头,才能在客户端使用 XMLHttpRequest 获取资源。