以下是使用XMLHttpRequest对象实现判断http://127.0.0.1:8080/index地址是否访问成功的示例代码:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8080/index');
xhr.onreadystatechange = function() {if (xhr.readyState === 4) { // 请求完成if (xhr.status >= 200 && xhr.status < 300) { // 成功返回console.log('地址访问成功');} else { // 失败返回console.log('地址访问失败');}}
};
xhr.send();
在上述代码中,我们创建了一个XMLHttpRequest对象,并使用其open方法打开一个GET请求,然后指定了onreadystatechange事件的处理函数,该处理函数在请求完成时会被调用。在处理函数中,我们检查XMLHttpRequest对象的状态和响应状态码,来判断地址是否访问成功。