【发布时间】: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处理程序的签名中声明cbSuccess和cbError。跨度> -
我想过。但是,我想为此添加一种返回成功或错误的方法。所以你不认为函数签名导致事件失败?
-
您希望他们在
_send上。您不希望它们出现在onreadystatechange处理程序上。不,我不认为这是问题所在。 (事实上,我认为问题根本不在引用的代码中,除非它从_getHTTPObject中抛出了一个你没有注意到的错误。) -
是什么让您认为 onreadystate 更改永远不会触发?除非它以 200 OK 响应进入状态 4,否则它不会做任何事情。
标签: javascript ajax require amd