[英]jQuery: return false inside of a function that calls ajax
对于这个特定的问题,我正在使用Tag-it https://github.com/aehlke/tag-it ,这是一个专用于使用标签的jQuery插件
我有一个标签列表,我正在使用ajax使用jQuery ui自动完成填充
我需要做的是,当ajax调用返回false时,向特定函数BeforeTagAdded返回false,这实质上是说数据库拒绝了此标记条目,而不在客户端浏览器中显示该标记
开发人员指出:“为澄清起见,只需在回调中返回false即可拒绝该标签。” 那就是我想要完成的
除了以下代码,我还尝试了什么:
Ajax调用返回的唯一结果是result:true或result:false,与此同时,除以下代码外,我还将处理一个jsfiddle
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
/等是事件处理程序。 在表示收到HTTP响应的事件到达之前,它们不会触发。
您不能从这些事件处理程序内部返回,也不能从beforeTagAdded
函数修改事件,因为beforeTagAdded
将在收到HTTP响应之前完成并返回。
您需要重新考虑您的方法。 这可能涉及始终取消beforeTagAdded
事件,但是要从Ajax事件处理程序内部以编程方式重新启动它。
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){
});
}
},
为什么不只是将AJAX与beforeTagAdded函数分开,而将beforeTagAdded用作回调?
像这样:
beforeTagAdded : function (event, ui, data) {
if (!ui.duringInitialization) {
// do something with the data
}
},
initAjax : function(event, ui) {
// make sure entity_id is defined
var entity_id = '';
$.ajax({
url: "handlers/tags.ashx",
dataType: "json",
data: {
idnumber: entity_id,
tag: ui.tagLabel,
operation:"tag"
}
}).complete(function (data) {
beforeTagAdded(event, ui, data);
});
}
然后,无论您在代码中的beforeTagAdded()
位置调用beforeTagAdded()
将其切换为initAjax()
。 现在,您可以在beforeTagAdded内部拥有ajax数据,以执行所需的任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.