【发布时间】:2015-09-29 14:01:51
【问题描述】:
我尝试使用 Node.js 测试我的 Ajax 代码。我以前没用过,所以我是新手。 这是我的代码:
<script>
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
function callServer() {
var url = "http://localhost:8888/";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
alert(response);
}
}
</script>
还有我的 Node.js 服务器:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Test");
response.end("Test");
}).listen(8888);
我运行带有属性的脚本:onclick="callServer()"。警报什么也没告诉我。谢谢。
【问题讨论】:
-
你确定你跑过节点吗?
node server之类的东西必须使用终端或同等设备发送。 -
@KJPrice 我敢肯定。我在文件末尾和函数(请求,响应)的开头添加了 console.log。
-
我创建了一个测试服务器,我看到了
No 'Access-Control-Allow-Origin' header is present on the requested resource,这个出现在你的console.log上了吗? -
@fuyushimoya 否。我使用 console.log 编辑的代码输出如下: node test.js 服务器已启动 收到请求(单击按钮后)
标签: javascript html ajax node.js