如何从jQuery的回调到父功能的数据

如何从jQuery的回调到父功能的数据

问题描述:

我正在使用jquery ui的拖放代码。在删除之后,getJSON请求会被执行以检查新数据并更新数据库。这工作正常,直到我的后端返回一个错误,因为我不能取消从匿名函数内的下降。如何从jQuery的回调到父功能的数据

如果有一个错误的后端返回JSON看起来像这样:

{"result":0} 

这是代码处理的下降:

$('.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)); 
    }}); 

我希望这是一个有点清晰。 任何想法? :)

那么,直到我找到了一个不太丑陋的解决方案,我将与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; 
} 

希望这可以帮助别人。

为什么不把你的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)); 
    } 
}); 
+0

嗯,在这种情况下使用全局变量并不好。 – acidtv 2010-09-28 17:10:49