使用本地主机测试Ajax [英] Testing Ajax using localhost
问题描述
我正在尝试使用Javascript测试一个简单的Ajax脚本,但没有收到响应.PHP脚本放置在本地服务器的 htdocs
文件夹中,而包含Ajax调用的HTML页面放置在我的桌面上.从服务器收到的 readyState
为4,但返回的状态为0,而不是200.
I am trying to test a simple Ajax script using Javascript and I'm not receiving a response. The PHP script is placed in the htdocs
folder of the local server and the HTML page that includes the Ajax calls is placed on my desktop. A readyState
of 4 is received from the server but the status returned is 0, not 200.
在Firefox状态下生成的错误:
The error generated on Firefox state:
NS_ERROR_DOM_BAD_URI:拒绝访问受限制的URI.
这是负责调用Ajax对象的代码部分:
Here is the section of code responsible for calling the Ajax object:
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);
}
}
}
任何人都可以洞悉我的问题吗?
Can anyone offer insight to my problem?
OSX 10.8.5
MAMP版本2.1.3
OSX 10.8.5
MAMP version 2.1.3
推荐答案
您说您的文件在桌面上.您无法打开本地文件(file://)并执行ajax.您需要通过Apache服务器(http://)访问该文件.
You say your file is on the desktop. You cannot open a local file ( file:// ) and do ajax. You need to access the file through your Apache server ( http:// ).
这篇关于使用本地主机测试Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!