使用localhost测试Ajax


Testing Ajax using localhost

我正在尝试使用Javascript测试一个简单的Ajax脚本,但没有收到响应。PHP脚本放在本地服务器的htdocs文件夹中,包含Ajax调用的HTML页面放在我的桌面上。从服务器接收到4的readyState,但返回的状态是0,而不是200。

Firefox上生成的错误状态:

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied.

以下是负责调用Ajax对象的代码部分:

var myRequest = getXMLHttpRequest();
function callAjax() {
    var url = "localhost/clock.php";
    var myRandom = parseInt(Math.random()*99999999);
    myRequest. open("GET", url + "?rand=" + myRandom, true);
    myRequest.onreadystatechange = responseAjax;
    myRequest.send(null);
}
function responseAjax() {
    if(myRequest.readyState == 4) {
        if(myRequest.status == 200) {
            var now = new Date();
            var localTime = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
            var serverTime = myRequest.responseText;
            document.getElementById("clock").innerHTML = "Server: " + serverTime + "<br />Local: " + localTime;
        } else {
            alert("An error has occurred: " + myRequest.statusText);
        }
    }
}

有人能洞察我的问题吗?

OSX 10.8.5
MAMP 2.1.3版

您说您的文件在桌面上。您不能打开本地文件(file://)并执行ajax。您需要通过Apache服务器(http://)访问该文件。