与同步ajax调用的返回值混淆

业余爱好者

我在从同步ajax调用返回值时遇到一些问题。我要返回的值是我为服务器响应创建的类。

这是AJAX代码:

function webRequest(file, data) {
    return $.ajax({
        url: "http://xxx.xx.xx.xxxx/xxxxx/"+file,
        type: "POST",
        data: data,
        asynch: false,
        error: function(jqXHR, textStatus, errorThrown){
            return new ServerResponse(false, errorThrown);
        },
        success: function(data, textStatus,  jqXHR){
            return new ServerResponse(true, data);
        },
        timeout: 7500
    });    
}

这是ServerResponse.js

var success = false;
var text = null;

var ServerResponse = function(success, text) {
    this.success = success;
    this.text = text || null;
};

ServerResponse.prototype.isSuccessful = function() {
    return this.success;  
};

ServerResponse.prototype.getData = function() {
    return this.text;
};

的返回值webRequest(..)如下:

Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}abort: function ( statusText ) {always: function () {complete: function () {done: function () {error: function () {fail: function () {getAllResponseHeaders: function () {getResponseHeader: function ( key ) {overrideMimeType: function ( type ) {pipe: function ( /* fnDone, fnFail, fnProgress */ ) {progress: function () {promise: function ( obj ) {readyState: 0responseText: ""setRequestHeader: function ( name, value ) {state: function () {status: 0statusCode: function ( map ) {statusText: "error"success: function () {then: function ( /* fnDone, fnFail, fnProgress */ ) {__proto__: Object VM2324 controllers.js:48

如何返回ServerResponse从ajax调用中创建实例?

ek

@fuyushimoya的答案几乎就在那里,只需从包装函数返回新实例化的服务器响应对象。

function webRequest(file, data) {
    var serverResponse;
    $.ajax({
        url: "http://xxx.xx.xx.xxxx/xxxxx/"+file,
        type: "POST",
        data: data,
        async: false,
        error: function(jqXHR, textStatus, errorThrown){
            serverResponse = new ServerResponse(false, errorThrown);
        },
        success: function(data, textStatus,  jqXHR){
            serverResponse = new ServerResponse(true, data);
        },
        timeout: 7500
    });
    return serverResponse;
}

这样你可以做

var sr = webRequest('some/file', someData);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章