简体   繁体   中英

Getting the responseText of the function in jQuery/AJAX

function foo(dataString){
        var jqXHR = $.ajax({
            type: "POST",
            url: "<?php echo site_url('c_device/check_empId'); ?>",
            data: dataString,
            dataType: 'json',
            cache: false,
            success: function(data){
                console.log(data);

                if(data.length == 0){
                    return 0;
                }       
                else{
                    $("#error_"+tr_id).html("Emp id exists");   
                    $("#"+tr_id).css("background-color","red");                 
                    return 1;
                }                    
            }

          });

        return jqXHR.responseText;
    }

how can I get the returned responseText of foo?

using

(in another jQuery event) var result = foo(dataString); doesn't work.

result will still be undefined.

It is best to use callbacks for what you're wanting to do.

var uiHelper = function () {

    var cachedText= {};

    var getText = function (options) {
        /// <summary>Returns HTML in a string format</summary>
        /// <param name="options" type="object">options{url:The url to the file with the HTML,successCallback:function,errorCallback:function,isAsync:true||false,cache:true|false}</param>

        function xhrSuccess() {
            if (this.cache) { cachedText[this.url] = this.responseText; };

            if (this.successCallback) {
                this.successCallback.apply(this.responseText, this.arguments);
            } else {
                return cachedText[this.url];
            };
        };
        function xhrError() {

            if (this.errorCallback) {
                this.errorCallback.apply(this.statusText);
            } else {
                return this.statusText;
            };
        };

        if (!cachedText[options.url]) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", options.url, options.isAsync);
            xmlhttp.cache = options.cache || false;
            xmlhttp.url = options.url;
            xmlhttp.onload = xhrSuccess;
            xmlhttp.onerror = xhrError;
            xmlhttp.successCallback = options.successCallback || undefined;
            xmlhttp.errorCallback = options.errorCallback || undefined;
            xmlhttp.send();
        } else {

            if (options.successCallback) {
                options.successCallback.apply(cachedText[options.url], this.arguments);
            } else {
                return cachedText[options.url];
            };
        };
    };

    return {
        getText: getText
    };
}();

-----Usage-----

var successCallBack = function () {

}
var errorCallBack= function () {

}
uiHelper.getText(
    {
        url: 'url',
        successCallBack: successCallBack,
        errorCallBack: errorCallBack,
        isAsync: true,
        cache: false
    })

This is because ajax is asynchronous, therefore you cant simply do like that. This issue can be solved in two ways

  1. Passing a callback function
  2. Using jquery's when

passing callback

function foo(dataString, callback){
    var jqXHR = $.ajax({
        type: "POST",
        url: "<?php echo site_url('c_device/check_empId'); ?>",
        data: dataString,
        dataType: 'json',
        cache: false,
        success: function(data){
            console.log(data);

            if(data.length == 0){
                return 0;
            }       
            else{
                $("#error_"+tr_id).html("Emp id exists");   
                $("#"+tr_id).css("background-color","red");                 
                return 1;
            } 
            callback (data);                   
        }
      });
}

using when

function foo(dataString){
    return $.ajax({
        type: "POST",
        url: "<?php echo site_url('c_device/check_empId'); ?>",
        data: dataString,
        dataType: 'json',
        cache: false
      });
}

 $.when (foo (dataString)).done (function(data){
            console.log(data);

            if(data.length == 0){
                return 0;
            }       
            else{
                $("#error_"+tr_id).html("Emp id exists");   
                $("#"+tr_id).css("background-color","red");                 

            }
            secondMethod (data);
        });

Hope this helps

I just added

async: false

in AJAX so it will be SJAX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM