我使用jQuery Tag-It将电子邮件字段设置为标记。我尝试在服务器端检查电子邮件是否有效,在我的情况下,api.php
,这样会产生如下响应:
{"status": "OK"}
或
{"status": "NG"}
我想在检查后拒绝无效的电子邮件添加到输入字段中,因此我将一个AJAX帖子添加到API调用中。但事件beforeTagAdded
需要立即布尔而不是异步回复。这是我的代码:
$('input[name=txt_email]').tagit({
beforeTagAdded: function(event, ui) {
if(!ui.duringInitialization) {
$.post('api.php', {
'request': 'check_email',
'entry': ui.tagLabel
}, function(response) {
if(response.status == 'OK') {
return true;
} else {
return false;
}
});
return false;
}
},
onTagExists (fn, callback) {
return false;
}
});
如何更改代码以拒绝无效代码?
UPDATE 我知道我可以将AJAX调用设置为同步模式,但不建议这样做,因为它在用户体验方面不好。
答案 0 :(得分:0)
我还在项目中使用了tag-it,希望这能解决您的问题。
我的解决方案:
beforeTagAdded: function(event,ui){
var temp = ui.tag.text();
var t11 = testcall();
alert("++++>>>"+t11);
return t11
}
function testcall(){
var result = true;//personal choice to set the boolean value
$.ajax({
'url':'/app/test',//your own url
'type':'POST',
'data':{'zx':123},// any data if needed
'async':false, // this is important for this task
success:function(response,Status,code){
alert("success >>");
result = false
},
error: function(jqXHR, exception) {
alert("error");
console.log(exception);
}
});
alert(result);
return result;
}