0

我正在使用 jquery ui 拖放代码。删除后,将执行 getJSON 请求以检查新数据并更新数据库。这工作正常,直到我的后端返回错误,因为我无法从匿名函数中取消删除。

如果出现错误,后端会返回如下所示的 json:

{"result":0}

这是处理drop的代码:

 $('.droppable').droppable({
  drop: function(event, ui) {
   $.getJSON('/roster/save', 'location_id=1', function (){
    if (data.result==0) {
     // now the drop should be cancelled, but it cannot be cancelled from the anonymous function
    }
   });

   // if data was available here I could check the result and cancel it
   if (data.result==0)
    return false; // this cancels the drop

   // finish the drop
   ui.draggable.appendTo($('ul', this));
  }});

我希望这有点清楚。有任何想法吗?:)

4

2 回答 2

0

好吧,在我找到一个不那么难看的解决方案之前,我将结合 jQuery .data() 方法使用同步 ajax 调用。所以代替 .getJSON() 调用:

$.ajax({  
 async: false,
 type: "POST",  
 url: "/roster/add",  
 data: 'location_id=1',  
 dataType: 'json',
 success: $.proxy(function(data) { $(this).data('tmp',data) }, $(this)),
});  

然后我可以检查存储数据的值并在必要时返回 false:

if (this).data('tmp').result != 1) {
 return false;
}

希望这可以帮助某人。

于 2010-09-27T15:16:14.330 回答
0

为什么不将您的 json-data 分配给一个新的全局变量,然后该变量应该在您的 getJson 函数之外可用?

$('.droppable').droppable({
    drop: function(event, ui) {
        $.getJSON('/roster/save', 'location_id=1', function (){
            jsonData = data;
        });

        // if data was available here I could check the result and cancel it
        if (jsonData.result==0)
        return false; // this cancels the drop

        // finish the drop
        ui.draggable.appendTo($('ul', this));
    }
});
于 2010-09-27T15:27:57.640 回答