我的任务是由我的团队构建一个系统,该系统将作为我们下一个将使用codeigniter和jquery开发的项目的程序化原型。因为我是网络编程的新手,我需要相当长的时间来解决问题。下面的代码困扰了我两天。如何防止jquery同时验证和提交数据
$(function() {
var bln_valid = true;
$('#btn_save').click(function() {
$('.warning-label').html('');
if ($('#txt_customer_code').val() == '') {
// did user provide customer code?
$('#lbl_customer_code').html('Customer Code has to be filled in.');
bln_valid = false;
} else {
// is the code unique?
$.post('<?php echo base_url()."index.php/customer/is_code_exists" ?>', {
txt_customer_code : $('#txt_customer_code').val()
},
function(data) {
if(data.error == undefined) {
if (data['code_exists'] == 1) {
$('#lbl_customer_code').html('Customer Code is not available.');
bln_valid = false;
}
} else {
$('#lbl_customer_code').html('Customer Code is not available.');
bln_valid = false;
}
},'json'
);
}
if (bln_valid == false) {
return false;
} else {
// insert the code to database
$.post('<?php echo base_url()."index.php/customer/add" ?>', {
txt_customer_code : $('#txt_customer_code').val(),
},
function(data) {
if(data.error == undefined) {
$('#lbl_customer_code').html(data['key']);
if (data['key'] == '') {
$('#lbl_customer_code').html('Failed Saving.');
return false;
} else {
$('#lbl_customer_code').html('Successfully saving.');
}
} else {
$('#lbl_customer_code').html('Failed Saving.');
return false;
}
},'json');
}
});});
所以我想验证客户代码的独特性,然后将其插入数据库。但似乎验证和插入代码都使用ajax,几乎同时执行。即使客户代码不唯一,bln_valid在插入开始时仍保留其“真”值。
- 有没有办法允许插入代码在验证完成后运行?我已经阅读了关于jquery的队列,但没有把握这个概念,并将其应用于解决我的问题。
- 有没有更有效的方法来达到验证和提交数据的目的?
我尽量不要使用任何插件,因为我被告知要尽可能少地使用任何外部作品。
感谢您的帮助。
在与我的队友讨论之后,我们同意给jQuery验证插件试一试。除了用于检查客户代码唯一性的ajax回调没有运行外,一切正常。我在这里发现了一个类似的问题http://bit.ly/lZsyZW。有任何想法吗? – dqiu
向我们展示您的代码....我希望您使用的是jQuery的$ .ajax –
abdul,感谢您的回复,并为我迟到的回复感到抱歉。我已经解决了我认为与我对jquery概念缺乏理解有关的问题。 (我不知道原因,所以我只是重写了部分代码)。 – dqiu