如何从jquery回调中获取数据给父函数
我正在使用 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));
}});
我希望这有点清楚。 有什么想法吗? :)
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? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,在我找到一个不太难看的解决方案之前,我将结合使用同步 ajax 调用和 jQuery .data() 方法。因此,而不是 .getJSON() 调用:
然后我可以检查存储数据的值,并在必要时返回 false:
希望这对某人有帮助。
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:
Then afterwards I can check the value of the stored data and return false if necessary:
Hope this helps someone.
为什么不将 json 数据分配给一个新的全局变量,然后该变量应该在 getJson 函数之外可用?
Why not assign your json-data to a new, global variable which should then be available outside your getJson-function?