jQuery:在调用ajax的函数内部返回false [英] jQuery: return false inside of a function that calls ajax
问题描述
对于此特定问题,我正在使用Tag-it https://github.com/aehlke/tag-它,这是专门用于使用标签的jQuery插件
for this specific problem i am using Tag-it https://github.com/aehlke/tag-it, a jQuery plug-in that is specific to using tags
我有一个标签列表,我正在使用ajax使用jQuery ui自动完成填充
I have a list of tags i am using ajax to populate using jQuery ui autocomplete
我需要做的是,当ajax调用返回false时,向特定的函数BeforeTagAdded返回false,实质上是说数据库拒绝了该标签条目,不在客户端浏览器中显示该标签
What I need to do is issue a return false to a specific function BeforeTagAdded when the ajax call returns false, essentially saying the database rejected this tag entry, do not show the tag in the client browser
开发人员指出为澄清起见,只需在回调中返回false即可拒绝该标签."那就是我想要完成的事情
The developer states that "To clarify, just return false in your callback to reject the tag." that is what i am trying to accomplish
除了以下代码外,我还尝试了什么:
What I have tried in addition to the below code:
- 将结果全球化到变量中,然后将ajax放入结果中,只返回未定义的
- 使用return false和/或event.preventDefault()+ stopPropagation()的组合
- 使用ajax调用的完成或完整方法
ajax调用返回的唯一结果是result:true或result:false 同时,除了下面的代码,我还将开发一个jsfiddle
The only thing the ajax call returns is a result:true or result:false in the meantime I will work up a jsfiddle in addition to the below code
beforeTagAdded: function(event, ui) {
if ( !ui.duringInitialization){ //do not fire on page initialization
$.ajax({
url: "handlers/tags.ashx",
dataType: "json",
data: {
idnumber: entity_id,
tag: ui.tagLabel,
operation:"tag"
}
}).done(function(data){
if(data.result == false){
event.preventDefault();
event.stopPropagation();
}
}).complete(function(data){
});
}
},
推荐答案
Ajax是异步的. complete
/done
/success
/etc是事件处理程序.在代表HTTP响应接收的事件到达之前,它们不会触发.
Ajax is asynchronous. complete
/ done
/ success
/ etc are event handlers. They won't fire until the event representing the receipt of the HTTP response has arrived.
您不能从这些事件处理程序内部返回,也不能通过beforeTagAdded
函数修改事件,因为beforeTagAdded
将在收到HTTP响应之前完成并返回.
You can't return from inside those event handlers, or modify the event from the beforeTagAdded
function because the beforeTagAdded
will have finished and returned before the HTTP response is received.
您需要重新考虑您的方法.这可能涉及始终取消beforeTagAdded
事件,但是从Ajax事件处理程序内部以编程方式重新启动.
You need to rethink your approach. This will probably involve always canceling the beforeTagAdded
event, but programmatically restarting it from inside the Ajax event handler.
beforeTagAdded: function(event, ui) {
if ( !ui.duringInitialization){ //do not fire on page initialization
event.preventDefault();
event.stopPropagation();
$.ajax({
url: "handlers/tags.ashx",
dataType: "json",
data: {
idnumber: entity_id,
tag: ui.tagLabel,
operation:"tag"
}
}).done(function(data){
if(data.result != false){
something(); // that would have happened if you hadn't called preventDefault before
}
}).complete(function(data){
});
}
},
这篇关于jQuery:在调用ajax的函数内部返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!