【发布时间】:2014-02-12 08:14:28
【问题描述】:
当我运行函数 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);
};
【问题讨论】:
-
我不太清楚你想说什么。通过为
httpRequest.onreadystatechange分配一个函数,您已经有了一个回调。究竟是什么行不通?该脚本当前的不良结果是什么? -
alert is alert('There was a problem with the request.');因为我在 alertcontents 中的一个 if 语句评估为假,我不希望这种情况发生
-
你能给我们一个
alertContents中的httpRequest对象的输出吗,例如console.log(httpRequest)?
标签: javascript xmlhttprequest httprequest