【问题标题】:XHR onreadystatechange never firesXHR onreadystatechange 从不触发
【发布时间】:2015-10-16 19:59:53
【问题描述】:

我有一个执行基本 Ajax 发布的 AMD 模块。它正在工作,它将发布到我的服务器 api,但是 onreadystatechange 事件不会触发。你能看出我做错了什么吗?...

define(['constants'], function (cons) {
    'use strict';

    function _getHTTPObject () {
        var http = false;
        // Use IE's ActiveX items to load the file.
        if (typeof ActiveXObject !== 'undefined') {
            try {http = new ActiveXObject("Msxml2.XMLHTTP");}
            catch (e) {
                try {http = new ActiveXObject("Microsoft.XMLHTTP");}
                catch (E) {http = false;}
            }
        // If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
        } else if (XMLHttpRequest) {
            try {http = new XMLHttpRequest();}
            catch (e) {http = false;}
        }
        return http;
    }

    function _send (url, params, cbSuccess, cbError) {
        var http = _getHTTPObject();
        http.open("POST", url, true);
        // Send the proper header infomation along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.onreadystatechange = function (cbSuccess, cbError) { 
            if (http.readyState === 4 && http.status === 200) {
                if (console) { console.log('xhrPost response:', http.responseText); }
            }
        }
        http.send(params);
    }

    return {
        send: _send
    };

});

【问题讨论】:

  • 注意:你根本不需要_getHTTPObject,除非你支持像IE6这样过时的浏览器。
  • 不是问题,而是下一个问题:你不想在onreadystatechange处理程序的签名中声明cbSuccesscbError。跨度>
  • 我想过。但是,我想为此添加一种返回成功或错误的方法。所以你认为函数签名导致事件失败?
  • 您希望他们在_send 上。您不希望它们出现在 onreadystatechange 处理程序上。不,我不认为这是问题所在。 (事实上​​,我认为问题根本不在引用的代码中,除非它从 _getHTTPObject 中抛出了一个你没有注意到的错误。)
  • 是什么让您认为 onreadystate 更改永远不会触发?除非它以 200 OK 响应进入状态 4,否则它不会做任何事情。

标签: javascript ajax require amd


【解决方案1】:

好的...所以在大量摆弄 javascript 之后,我终于看到了这个问题。我正在测试的服务器 api 发布路由没有返回成功响应,只是出错了,所以花了很长时间才看到。

所以上面的代码没问题:-/

如果有人感兴趣,这里是服务器节点路由代码。我必须在播放器保存成功后添加 return res.json(... 行才能获得正确的 readyState 来触发...

app.post('/api/player/create', function (req, res) {
    var player = new Player({
            'firstName': req.body.firstName,
            'lastName': req.body.lastName,
            'handle': req.body.handle,
            'email': req.body.email
        });
    player.save(function (err) {
        if (!err) {
            log.logOK('New player joined! (%0)', req.body.handle);
            return res.json({ 'error': '' }); // <== This was missing
        } else {
            log.logER('Create new player failed, error (%0): %1', req.player.handle, err);
            return res.json({ 'error': err });
        }
    });
});

【讨论】:

    猜你喜欢
    • 2015-05-29
    • 1970-01-01
    • 2018-01-19
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2015-04-21
    • 1970-01-01
    相关资源
    最近更新 更多