gpt4 book ai didi

javascript - XHR onreadystatechange 从不触发

转载 作者:行者123 更新时间:2023-11-30 00:25:21 27 4
gpt4 key购买 nike

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

});

最佳答案

好的...所以在摆弄了很多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 });
}
});
});

关于javascript - XHR onreadystatechange 从不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31639448/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com