hurriedly% 2017-04-13 17:04 采纳率: 100%
浏览 24

在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.

  • 写回答

1条回答 默认 最新

  • weixin_33682790 2017-04-14 10:20
    关注

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

报告相同问题?