$ .deferred无法按预期工作

时间:2017-04-18 21:30:53

标签: javascript jquery jquery-deferred

在某个按钮的click事件中,我正在调用函数a(),其中包含下面提到的Ajax调用,在我成功使用$.Deferred时。它在第一次点击按钮时工作得非常好,但是当我点击第二,第三,第四......或第n次按钮时它没有按预期工作(它根本没有进入确认功能)。我做错了什么。先感谢您。

$.ajax({
            type: "GET",
            url: "some url",
            data: {
                parameters
            },
            success: function (result) {
                 //result is an Array object. for example **result:Array[3]**, further expand result will be like this **result[0]:Array[19], result[1]:Array[39], result[2]:Array[15]**
                var defer = $.Deferred();

                function confirmation(result) {
                    if (result.length > 1) {

                $('#field' + questionID).append('<div id=dialog></div>');
                $("#dialog").append('<div id=grid></div>');

                $("#dialog").kendoDialog({
                    modal: true,
                    visible: false,
                    draggable: true,
                    closable: false,
                    title: "Please Select One Submission",
                    maxWidth: 500,
                    //maxHeight:300,
                    animation: {
                        open: {
                            effects: "slideIn:down fadeIn",
                            duration: 500
                        },
                        close: {
                            effects: "slide:up fadeOut",
                            duration: 500
                        }
                    },
                    actions: [
                        { text: 'OK', primary: true, action: onOK }
                    ]
                });

                $("#grid").kendoGrid({
                    dataSource: {
                       data: result,
                        schema: {
                            data: function (result) {
                                return $.map(result, function (item) {
                                    return $.map(item, function (innerData) {
                                        for (var i = 0; i < displayFields.length; i++) {
                                            if (displayFields[i] == innerData.FieldIDString) {
                                                return {
                                                    EntryGroupID: innerData.EntryGroupID,
                                                    FieldTextString: innerData.FieldTextString,
                                                    EntryValue: innerData.EntryValue
                                                }

                                            }
                                        }
                                    });

                                });
                            }
                        },
                        pageSize: 2,
                        group: { field: "EntryGroupID" }                           
                    },
                    filterable: {
                        mode: "row"
                    },
                    pageable: {
                        refresh: true,
                    },
                    noRecords: {
                        template: "No records to display"
                    },
                    groupable:false,
                    //scrollable: true,
                    selectable: true,
                    columns: [{
                        field: "EntryGroupID",
                        title: "Submissions",
                        filterable: {
                            cell: {
                                operator: "contains"
                            }
                        }
                    }, {
                        field: "FieldTextString",
                        title: "Questions",
                        filterable: {
                            cell: {
                                operator: "contains"
                            }
                        }
                    }, {
                        field: "EntryValue",
                        title: "Answers",
                        filterable: {
                            cell: {
                                operator: "contains"
                            }
                        }
                    }]
                });

                var wnd = $("#dialog").data("kendoDialog");
                wnd.wrapper.find('.k-dialog-title').css('background', CIMSFields.backgroundColour).css('color', CIMSFields.textColour).css('width','100%').css('text-align','center');
                wnd.open().center(true);

                //in this function i'm waiting for user response which they will choose one array object based on this value **Confirmation** function will get the data.
                function onOK(e) {
                    var data = [];
                    var grid = $("#grid").data("kendoGrid");
                    var selectedItem = grid.dataItem(grid.select());
                    if (selectedItem != null) {
                        $.map(result, function (item) {
                            if (selectedItem.EntryGroupID == item[0].EntryGroupID) {
                                data.push(item);
                                defer.resolve(data);
                            }
                        });
                    }
                    else {
                        defer.resolve(data);
                    }
                    wnd.close();
                }
            }
            else
            {
                defer.resolve(result);
            }
            return defer.promise();
       }        
       alert(defer.state());        
       confirmation(result).then(function (data) {
          //it never reach here except first time
             alert(defer.state());                        
             alert(data);// data is the user selected value from the grid.                        
          })
      }
});

2 个答案:

答案 0 :(得分:0)

如果result是数组,则.empty不是Array属性或方法。 $.Deferred()不是必需的,$.ajax()返回一个jQuery promise对象。

您可以检查预期数组的.length,或.then()链接到a()来电的预期对象的属性。另外,链.fail()来记录和处理可能发生的错误。

function a(/* parameters */) {
  // note, we are `return` ing `jQuery.ajax()` call,
  // which returns a jQuery promise object
  return $.ajax({type: "GET", url: "some url", data: {parameters}})

}

a()
.then(function(result, textStatus, jqxhr) {
  console.log(result.length, jqxhr.state());
  if (result.hasOwnProperty("empty")) { console.log(result.empty); }
  else { console.log("result does not have property \"empty\""); };
})
// log, handle errors here
.fail(function(jqxhr, textStatus, errorThrown) {
  console.log(textStatus, errorThrown, jqxhr.state());
});

答案 1 :(得分:0)

found my answer here

基本上我的需要是我必须在继续进行之前等待函数中的用户响应。谢谢所有花时间回答我的问题的人。我感谢您的时间和精力。最重要的是,我现在根本没有使用deferred