【发布时间】:2015-04-09 12:50:02
【问题描述】:
我正在从 html 到 nodejs 进行 ajax 调用以从服务器检索数据,数据正在从服务器返回但在浏览器中它没有显示
//html code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script>
function changeText1() {
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange=function() {
if(myRequest.status==200 && myRequest.readystate==4) {
console.log("successfully received ");
var name=JSON.parse(myRequest.responseText);
console.log(name);
document.getElementById("myDiv").innerHTML = name.title;
} else {
console.log("Cannot process");
}
}
myRequest.open("GET","http://localhost:3000/endpoint",true);
myRequest.send(null);
}
</script>
</head>
<body>
<div id="myDiv">Hello welcome</div>
<button type="button" onclick="changeText1()">Change Content</button>
</body>
</html>
//服务器端代码(在nodejs中)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(express.static(__dirname+"/"));
app.get('/endpoint', function(req, res) {
var obj = {};
obj.title = 'Ajax project';
//obj.data = 'Welcome';
res.header('Content-type','application/json');
res.header('Charset','utf8');
console.log(JSON.stringify(obj));
res.send(JSON.stringify(obj) );
});
app.listen(3000);
console.log("Server started");
正在从服务器检索数据 但是控件无法进入
if(myRequest.status==200 && myRequest.readystate==4)
显示器无法处理
【问题讨论】:
-
做一个 console.log("Status:" + myRequest.status + "readyState: " +myRequest..readyState) 看看你得到了什么。
-
除非我忽略了某些事情,否则您从不将您的请求发送到任何地方?
标签: javascript html ajax node.js express