我正在进行从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)
并且显示无法处理
答案 0 :(得分:1)
readyState是用camelCasing编写的,而不是&#39; readystate&#39;这就是为什么你看不到结果,&#39; readystate&#39;未定义。我强烈建议你使用&#39; ===&#39;而不是&#39; ==&#39;在你的if语句中。
此外,我会在您打开请求后编写此代码。
myRequest.onreadystatechange = function () {
if(myRequest.readyState === 4) {
if(myRequest.status === 200) { //DO STUFF}
}
}