【问题标题】:How to get data from jquery callback to parent function如何从jquery回调中获取数据到父函数
【发布时间】:2010-09-27 11:05:35
【问题描述】:

我正在使用 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));
  }});

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

【问题讨论】:

    标签: jquery-ui callback scope droppable


    【解决方案1】:

    好吧,在我找到一个不那么难看的解决方案之前,我将结合 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;
    }
    

    希望这对某人有所帮助。

    【讨论】:

      【解决方案2】:

      为什么不将您的 json 数据分配给一个新的全局变量,然后该变量应该在您的 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));
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-28
        • 1970-01-01
        • 1970-01-01
        • 2019-08-30
        相关资源
        最近更新 更多