Javascript 意外空白的Ajax响应文本
我尝试用Node.js测试我的Ajax代码。我以前没用过,所以我是新手。 这是我的密码:Javascript 意外空白的Ajax响应文本,javascript,html,ajax,node.js,Javascript,Html,Ajax,Node.js,我尝试用Node.js测试我的Ajax代码。我以前没用过,所以我是新手。 这是我的密码: <script> var xmlHttp = false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = n
<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>
我使用以下属性运行脚本:onclick=“callServer()”。警报什么也没告诉我。谢谢。尝试以下更改:
xmlhttp.send(空)代码>
发送到xmlhttp.send()代码>
改变
var xmlHttp=false
tovar xmlHttp=null代码>
如有其他更改,请更改为如下所示:
if(window.XMLHttpRequest){
//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
否则{
//IE6、IE5的代码
xmlhttp=newActiveXObject('Microsoft.xmlhttp');}
下面看起来有些多余,您可能需要对其进行注释:
//response.write(“Test”)代码>
确保节点正在运行
祝您好运。您的代码工作正常,问题是您在不同的域或端口上运行客户端,然后服务器运行
尝试在上运行您的客户端
编辑:
使用Express package非常简单:
var app = require('express')();
app.get('/', function(req, res) {
res.send('Test');
});
app.get('/index.html', function(req, res) {
res.sendfile('index.html');
});
app.listen(8888, function() {
console.log('Server started at port 8888');
});
编辑#2
没有明示:
var http = require('http'),
fs = require('fs');
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', function(err, data) {
res.writeHeader(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
}).listen(8888);
server.on('request', function(req, res) {
if(req.url == '/test') {
res.writeHeader(200, { 'Content-Type': 'text/plain' });
res.write('Test');
res.end();
}
});
编辑#3
要为静态资产提供服务,请使用如下中间件:
var express = require('express'),
app = express();
app.use(express.static(__dirname + '/public'));
您应该将资产放在根目录中的public
目录中。是否确实运行了节点?必须使用终端或等效设备发送类似于节点服务器的内容。@KJPrice我确定。我在文件末尾和函数(请求、响应)的开头添加了console.log。我创建了一个测试服务器,发现请求的资源上没有“Access Control Allow Origin”头,这是否出现在您的console.log上?@fuyushimoya No.我用console.log编辑的代码输出:node test.js服务器已启动,收到的请求(单击按钮后)没有帮助,很遗憾。请尝试此更改:from:response.writeHead(200,{“内容类型”:“text/plain”});to:response.writeHead(200,{'Content-Type':'text/html'});如何在localhost:8888中运行我的客户端?我没有在任何地方部署我的客户端。我的意思是,我把所有东西都放在电脑上,我在上面运行.html文件。这段代码很有效,非常感谢。但是有没有办法不用Express呢?因为我在Express中丢失了我的js、css和字体。
var express = require('express'),
app = express();
app.use(express.static(__dirname + '/public'));