当我运行函数alertContents时,else正在评估,我不希望发生这种情况,我如何注册回调以等待httprequest响应?基本上,httprequest onreadystatechange需要使用回调来等待对alertcontents函数的响应,评估第一个条件并最终从message.js中设置的body变量中提醒“hello json”
<html>
<header><title>This is title</title></header>
<body>
<script type="text/javascript" src="message.js" ></script>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() { makeRequest('message.js'); };
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = cbalertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function cbalertContents(){
alertContents();
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var resDataString = httpRequest.responseText;
var resData = JSON.parse(resDataString);
var msg = resData.msg;
alert(msg);
} else {
alert('There was a problem with the request.');
}
}
}
})();
我的message.js如下,我试图从json字符串中获取msg属性
var http = require('http');
var responseObject = { msg: 'Hello JSON.' };
var responseString = JSON.stringify(responseObject);
var body = new Buffer(responseString, 'utf-8');
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(body);
};
答案 0 :(得分:1)
我认为回调实现没有任何问题。如果要使用Node.js生成JSON响应,可以尝试下面的实现。
var http = require('http');
var responseObject = {msg:"Hello JSON."};
var responseString = JSON.stringify(responseObject);
var body = new Buffer(responseString, 'utf-8');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json',"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"X-Requested-With"});
res.end(body);
}).listen(1337, "127.0.0.1");
console.log("Node server is running");
如果没有跨域关注,您可以从响应标头中删除“Access-Control-Allow-Origin”:“*”和“Access-Control-Allow-Headers”:“X-Requested-With”。
并更新您的ajaxButton点击处理程序网址参数。
document.getElementById("ajaxButton").onclick = function() { makeRequest('http://127.0.0.1:1337/'); };
启动节点服务器(节点message.js),“Hello JSON”消息将按预期显示。
截图:
希望这有用。