简体   繁体   中英

Deferred In JQUERY | AJAX

My Requirement is return data using "SetUnit()" function but this function is contain async AJAX services so i am using Deferred suggested in this ( http://jsfiddle.net/b69ubLa0/21/ ) link. but this is not working on my requirement.

Code......

Function

function SetUnit(query) {
            var $q = new $.Deferred();
            var oData = [];
            var filter = JSON.stringify({ 'param': query });
            $.ajax({
                type: "POST",
                url: '../WebService.asmx/ExecuteReader',
                contentType: "application/json; charset=utf-8",
                data: filter,
                dataType: "json",
            }).fail(function (jqXHR, textStatus, errorThrown) {
                $q.reject(jqXHR, textStatus, errorThrown);
            }).done(function (data, textStatus, jqXHR) {
                return $q.resolve(data);
            });
            return $q.promise();
        }

Call Function 1

var oUNIT_NAME = SetUnit(query).done(function (data) { return data; });

Call Function 2

 var oUNIT_NAME = SetUnit(query);

call function using 2 style.

And This "oUNIT_NAME" var is using for binding many drop downs.

Services Return JSON OBJECT

[{id:1,name:a},{id:1,name:a},{id:1,name:a},{id:1,name:a}]

Note : this is working if i am add (async: false) in AJAX setting but this not a good practice and this block my UI.

I hope this helps. I'm not a pro about deferred objects but i believe this does what you need.

updated

Working Fiddle

var oUNIT_NAME = {};
function SetUnit(query) {
    var $q = new $.Deferred()
    $q.promise(oUNIT_NAME);
    oUNIT_NAME.done(function(data) {
        //Bind your dropdowns
        alert(JSON.stringify(data));
    }).fail(function(jqXHR, textStatus, errorThrown) {
        //Alert user
        alert(errorThrown);
    });
    var oData = [];
    var filter = {
        json: JSON.stringify({
            data: query
        })
    };
    return $.ajax({
        cache: false,
        type: "POST",
        url: '/echo/json/',
        data: filter,
        dataType: "json"
    }).fail(function(jqXHR, textStatus, errorThrown) {
        $q.reject(jqXHR, textStatus, errorThrown);
    }).done(function(data, textStatus, jqXHR) {
        $q.resolve(data);
    });
}

SetUnit({
    param: 123
})
$("button").click(function() {
    SetUnit({
        param: 456
    })
});

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