AJAX不能在localhost上工作

时间:2012-05-17 10:41:32

标签: javascript ajax

我正在尝试使用AJAX示例,但我无法使其正常工作。你能在XAMPP上运行吗?

我有三个文件,message.txt,index.html,ajaxtest.js。当您单击超链接时,它应弹出一个包含message.txt内容的内容。 (所有文件都在同一目录中)

的index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
  <head>
  <title> Using XMLHttpRequest</title>
  <script type="text/javascript" src="ajaxtest.js"></script>
  </head>
  <body>
    <p>
      <a href="message.txt" onclick="grabFile(this.href); return false;">
Click here
</a>
</p>
</body>
</html>

ajaxtest.js

function getHTTPObject() {
  var xhr = false;
  if (window.XMLHttpRequest) {  //see if a XMLHttpRequest exists
    xhr = new XMLHttpRequest();  //if it exists change "xhr" to a new instance of the object
  }
  else if (window.ActiveXObject) {  //see if ActiveX exists (for IE)
    try {  //Allows newer versions of IE to use the newer ActiveX object
      xhr = new ActiveXObject("Msxml2.AMLHTTP");  //if it exists change "xhr" to a new instance of the object
    }
    catch(e) { //catches an error and resets "xhr" to false
      try {  //Allows older versions of IE to fall back onto the older version using "try...catch"
        xhr = new ActiveXObject("Microsoft.XMLHTTP");  //if it exists change "xhr" to a new instance of the object
      }
      catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}

function grabFile(file) {
  var request = getHTTPObject();
  if (request) {
    request.onreadystatechange = function() {
      displayResponse(request);
    };
    request.open("GET", file, true);
    request.send(null);
  }
}

function displayResponse(request) {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
      alert(request.responseText);
    }
  }
}

2 个答案:

答案 0 :(得分:4)

出于安全原因,JavaScript对客户端上文件系统的访问受到限制!你可以read more here

如果您使用的是Google Chrome,则必须使用-allow-file-access-from-files命令启动可执行文件:

chrome.exe -allow-file-access-from-files

FireFox可能有类似的配置

更新: 检查您的代码,我认为您正在将request.statusOK(200)和Not Modified(304)标头进行比较!这些是从Web服务器返回的HTTP响应头,因此当您在Web服务器上运行代码时,必须检查响应头,否则,当使用file:///协议在本地运行时,您始终会获得{ {1}}响应标题

这是一种解决方法,您可以检查域,如果您在本地运行,则无需检查响应状态:

0

答案 1 :(得分:0)

正如我尝试过您的示例,您的请求对象未达到状态4并再次使用。 在下面的代码之前检查request.status,它总是得到0值。这就是为什么你的脚本没有提醒响应的原因。

if (request.status == 200 || request.status == 304) {
  alert(request.responseText);
}

选中此解决方案:http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/

希望有所帮助。