【发布时间】:2010-05-06 14:12:15
【问题描述】:
如果单击提交按钮,请阻止默认操作并查看字段“account_name”是否已在使用中。如果$.get() 返回结果,则提醒用户该结果。如果没有,请使用id="add_account_form" 提交表单。
我的问题是我的 else{} 语句没有提交表单。单击提交时我没有得到响应并且没有返回值。
另外,我想将代码更改为 $("#add_account_form").submit(..) 而不是 .click(),但是在稍后尝试在脚本中提交表单时会导致问题吗?
<script type="text/javascript">
$(document).ready( function () {
$("#submit").click( function () {
var account_name = $("input[name=account_name]").val();
$.get(
"'.url::site("ajax/check_account_name").'",
{account_name: account_name},
function(data){
if(data.length > 0){
confirm( "The account name you entered looks like the following:\n"
+data+
"Press cancel if this account already exists or ok to create it."
);
}else{
$("#add_account_form").submit();
}
});
return false;
});
});
</script>
<p>
<input type="submit" id="submit" class="submit small" name="submit" value="Submit" />
</p>
</form>
感谢您的帮助。
编辑
所以遇到我的问题的人,$.get() 是异步的,所以它总是返回 false 或 true,具体取决于 submitForm 的定义。但是,$.ajax() 允许将 async 设置为 false,这允许函数在继续之前完成。看看我的意思:
$(document).ready( function () {
$("#add_account_form").submit( function () {
var submitForm = true;
var account_name = $("input[name=account_name]").val();
$.ajax({
type: "GET",
async: false,
url: "'.url::site("ajax/check_account_name").'",
data: ({account_name: account_name}),
success:
function(data){
if(data.length > 0){
if(!confirm( "The account name you entered looks like the following:\n"
+data+
"Press cancel if this account already exists or ok to create it."
)){
submitForm = false;
}
}
}
});
if (submitForm == false ) {
return false;
}
});
});
感谢您的帮助@Dan
【问题讨论】:
-
这个
$("#add_account_form").submit();到底应该做什么!? ;-) -
乍一看好像你想重新提交表单,如果第一次尝试失败!不是吗!?但是如果您的表单第一次出现错误,为什么它应该在下一次工作!? ;-)
标签: jquery form-submit