【问题标题】:how do I use callbacks to wait for httprequest?如何使用回调来等待 httprequest?
【发布时间】: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


【解决方案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 点击​​处理程序 url 参数。

document.getElementById("ajaxButton").onclick = function() { makeRequest('http://127.0.0.1:1337/'); };

启动您的节点服务器 (node message.js),“Hello JSON”消息将按预期显示。

截图:

希望这有帮助。

【讨论】:

  • 这工作正常,但我正在尝试使用 main 来运行服务器并处理请求,我将编辑并放置我的 main.js。
猜你喜欢
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2020-01-12
相关资源
最近更新 更多