Javascript 在Ajax中打开网页并检查状态代码
我有一个代码,用来检查页面是否已加载,然后通知我状态。 由于某种原因,该代码将不起作用。 如果你能看一下,告诉我我做错了什么,我将不胜感激。 期待答案Javascript 在Ajax中打开网页并检查状态代码,javascript,ajax,http,Javascript,Ajax,Http,我有一个代码,用来检查页面是否已加载,然后通知我状态。 由于某种原因,该代码将不起作用。 如果你能看一下,告诉我我做错了什么,我将不胜感激。 期待答案 var xmlHttp = createXmlHttpRequestObject(); function createXmlHttpRequestObject(){ var xmlHttp; if(window.ActiveXObject){ try{ xmlHttp = new ActiveXOb
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Error");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
xmlHttp.open("GET", "djhgkjshgkjsd.com", true);
xmlHttp.onreadystatechange = handleServerResponse;
}
else{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
alert("Hi..."); // This is just to test where my code fails
}else{
alert('Something is wrong!');
}
}
}
你这里有几个问题 主要的一点是,您从不
send()
HTTP请求
但是,您还有一些其他问题:
- 您从不调用
进程
- 您正在轮询readyState,而不是使用readystatechange事件处理程序
- 只有当readyState已经
(失败)或0
(完成)时,才能分配readystatechange处理程序,因此永远不会调用它4
- 您拥有看起来像绝对URI的内容,但是
- 缺少方案(例如http://)
- 您在尝试访问其他域的数据时将遇到同源策略限制
// I've removed the code to support IE7 and earlier.
// Those browsers are dead and the approach you were using was
// poor anyway (it prioritised non-standard approaches over
// standard instead of the other way around);
var xmlHttp = new XMLHttpRequest();
// Warning Cross-Origin request. The server must grant permission
// for your site to access the data using CORS for this to work
xmlHttp.open("GET", "http://example.com", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
function handleServerResponse() {
// Use a local variable. Globals are horrible
// and work poorly with event driven programming
var xmlResponse;
if (this.readyState == 4) {
if (this.status == 200) {
xmlResponse = this.responseXML;
alert("Variable populated");
} else {
alert('Something is wrong!');
}
}
}
定义“将不起作用”。它在哪里/如何失败?非常感谢!但是“//警告跨源请求”是什么意思?服务器必须授予权限//才能让您的站点使用CORS访问数据以使其正常工作?默认情况下,您的站点不允许指示用户的浏览器从另一个站点获取数据(这可能是他们只有在登录到另一个站点时才能访问的私有数据)并将这些数据提供给JavaScript。我如何更改这些数据?(如有可能)。我的最终目标是能够判断用户是否有正在运行的服务器。通过访问一个不存在的页面,我会得到一个浏览器错误或一个默认服务器错误(这就是我试图读取的内容)。无法从JavaScript中获取关于任意服务器的信息。改为从服务器执行检查。你可以创建一个Web服务来完成它,并从JS访问它。在Ajax中,我无法作为用户请求网页?