与同步ajax调用返回值混淆

时间:2015-07-05 15:35:39

标签: javascript jquery 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

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

1 个答案:

答案 0 :(得分:3)

@ 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);