我正在使用 jquery+Ajax 验证重复名称。一切正常,除了表单在一切返回 true 后不提交
发生了什么
- 如果没有输入名字,警告框会显示名字是 必需 --> 这里没问题
- 如果找到重复的名字,警告框会显示名字 已存在且表单未提交 --> 这里没问题
- 如果没有找到重复的名字,就会出现警告框(以证明
else
部分条件有效),但 表单无效 提交。我希望表单继续并在此else
中提交自己 部分
jQuery 代码
$('#form1').submit(function(){
var name = $('#shelf_name').val();
if(name == '')
{
alert('Shelf name is required');
$('#shelf_name').focus();
}
else
{
$.ajax({
type:'post',
url:'check-duplicate-shelf-name.php',
data:{'name':name},
context:this,
success:function(data)
{
if(data == 'stop')
{
alert('Shelf name already exists'); // working if duplicate name is found
}
else
{
alert('else working?'); // alert box is showing up if name is not duplicate
this.submit(); // but after alert, this line not executing
}
}
});
}
return false;
});
HTML 表单标签
<form action="add-shelf-post.php" method="post" id="form1">
check-duplicate-shelf-name.php 页面
<?php
include 'confignew.php';
$name = $_POST['name'];
// peforming database operations
.
.
.
// and then
if($db->num_rows($q) == 0)
{
echo 'go';
}
else
{
echo 'stop';
}
我遗漏了一些非常明显的东西。希望这里有人能指出这一点。
用Firefox中的Firebug查看后,确实报错了。当我使用 Chrome 进行测试时,它没有出现。这是屏幕截图。
最佳答案
我会在运行时使用 jQuery 验证器检查它,而不是在提交时检查它,但另一种方法是进行 Rest Style 调用。我认为没有必要为了检查 1 个字段而发布完整的表格。
$('#form1').submit(function(){
//Check not empty
if(!$('#shelf_name').val()) {
alert('Shelf name is required');
$('#shelf_name').focus();
} else {
//Valiate Rest style call
$.getJSON("check-duplicate-shelf-name.php/".concat($('#shelf_name').val()), function(data) {
//If you only have 2 states I would return boolean to faster check ex: if(!data){
if(data == 'stop') {
// working if duplicate name is found
alert('Shelf name already exists');
} else {
alert('else working?'); // alert box is showing up if name is not duplicate
$('#form1').submit(); // but after alert, this line not executing
}
});
}
return false;
});
当我在评论中说您可以不使用 $(this).submit(); 手动发布表单时,我指的是:
$.ajax({
url: "./myurl",
cache: false,
type: "POST",
data: $("#form1").serialize(),
success: function(){
console.log("Submit successful");
}
});
关于javascript - 表单未在 $.ajax 成功函数中提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12017823/