Confusion with return values ​​from synchronous ajax call

I am having trouble returning a value from a synchronous ajax call. The value I want to return is the class I created for the server response.

Here's the AJAX code:

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

      

Here's 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;
};

      

The return value webRequest(..)

looks like this:

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

      

How can I get back the instance ServerResponse

created from the ajax call?

+3


source to share


1 answer


@ fuyushimoya's answer is almost there, just return the newly created server response object from the wrapper function.

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;
}

      



This way you can do

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

      

+3


source







All Articles