XHR onreadystatechange永远不会激发

时间:2015-07-26 16:43:15

标签: javascript ajax require amd

我有一个基本的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
    };

});

1 个答案:

答案 0 :(得分:1)

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

所以上面的代码很好: - /

如果有人感兴趣,这是服务器节点路由代码。我必须在播放器保存成功后添加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 });
        }
    });
});