我在ajax中遇到了一个问题。场景是:我想在输入电子邮件时验证用户是否有空。因此,我在javascript中创建了一个函数,其中包含一个Ajax脚本。下面是我的代码:
$('#username').keyup(function () {
var email = $(this).val();
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
});
});我的问题是:当我输入任何单词时,它会调用keyup函数,然后即使数据为空,它也会成功。我希望只有在数据正确完成的情况下,才能让它传递到成功。谢谢。
发布于 2016-08-09 01:28:08
试试Following..Hope吧,它按你想要的那样工作...
$('#username').keyup(function () {
var email = $(this).val();
if(email != "") {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
// Check response data...
if(data == 'true') {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
}
});
}
}); 发布于 2016-08-09 00:46:48
在做任何事情之前,尝试一些错误检查。因此,success回调将被调用(您不能有条件地停止它),但内部代码将被阻止。
使用以下代码封装success事件处理程序中的所有内容,以便仅在data不为null (空字符串)时执行:
if(data != "") {
// action here
}我不确定您所说的“数据为空”是什么意思,因此上面所示的简单的空字符串条件可能不足以检查数据是否为空。这将简单地检查data参数是否为空。
https://stackoverflow.com/questions/38834516
复制相似问题