开发者

How to get data from jquery callback to parent function

I'm using the jquery ui drag/drop code. Upon a drop开发者_运维知识库 a getJSON request gets executed to check the new data and update the database. This works fine, until my backend return an error, because I can't cancel the drop from within the anonymous function.

If there's an error the backend returns json that looks like this:

{"result":0}

This is the code handling the 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));
  }});

I hope this is a bit clear. Any ideas? :)


Well, until I've found a less ugly solution I'll be using a synchronous ajax call in combination with the jQuery .data() method. So instead of the .getJSON() call:

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

Then afterwards I can check the value of the stored data and return false if necessary:

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

Hope this helps someone.


Why not assign your json-data to a new, global variable which should then be available outside your getJson-function?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜