Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jqueryajax监听器_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript jqueryajax监听器

Javascript jqueryajax监听器,javascript,jquery,ajax,Javascript,Jquery,Ajax,如果我有对象myApi和execute函数 var api = new myApi(); api.execute(); 在execute内部,我有(*那是myApi实例) 如何创建回调/侦听器以便执行此操作 var api = new myApi(); api.execute(); var result = api.getResult(); var statusCode = api.getStatusCode(); switch(statusCode) {...}; 如果我这样做的话,下面两

如果我有对象
myApi
execute
函数

var api = new myApi();
api.execute();
execute
内部,我有(*
那是
myApi
实例)

如何创建回调/侦听器以便执行此操作

var api = new myApi();
api.execute();
var result = api.getResult();
var statusCode = api.getStatusCode();
switch(statusCode) {...};

如果我这样做的话,下面两行代码是在
ajax
调用完成之前执行的(
complete
尚未调用),因此我有
未定义的
变量。

你不能这样做,除非你强制ajax请求同步(这可能是个坏主意)。您需要附加某种回调方法,还可以使用一些jQuery
Deferred
magic

因此,返回封装了延迟的
jqXHR
对象:

function execute() {
    return $.ajax({
        type: this.getRequestMethod(),
        data: this.getDataParams(),
        complete: function(xmlHttp){
            that.setResult(jQuery.parseJSON(xmlHttp.responseText));
            that.setHttpStatus(xmlHttp.status);
        },
        url: this.getUrl(),
        beforeSend: setHeader
    });
}
然后像这样使用它

var api = new myApi();
var req = api.execute();
req.done(function( data ) {

});
req.fail(function( xhr ) {
    var statusCode = xhr.status; // etc.
});

您不能这样做,除非您强制AJAX请求同步(这可能是个坏主意)。您需要附加某种回调方法,还可以使用一些jQuery
Deferred
magic

因此,返回封装了延迟的
jqXHR
对象:

function execute() {
    return $.ajax({
        type: this.getRequestMethod(),
        data: this.getDataParams(),
        complete: function(xmlHttp){
            that.setResult(jQuery.parseJSON(xmlHttp.responseText));
            that.setHttpStatus(xmlHttp.status);
        },
        url: this.getUrl(),
        beforeSend: setHeader
    });
}
然后像这样使用它

var api = new myApi();
var req = api.execute();
req.done(function( data ) {

});
req.fail(function( xhr ) {
    var statusCode = xhr.status; // etc.
});