1
我是jQuery的新手,我尝试验证表单。如果标题已经在数据库中,我想用ajax和php进行搜索。下面的代码编写了我的作品,如果标题已经在db中,则返回1,否则返回0。在此之后,我想添加一个类到标题文本框。最后,我会搜索标题textfield是否有该类,如果是true,则停止该表单,否则提交。jQuery - AJAX表单验证
即使php返回1,我的脚本仍然会提交表单。我做错了什么?
// Process PHP file
$.ajax({
beforeSend: function()
{
// Show loading
$('#msg_search_load').removeAttr('style');
},
type: "GET",
url: "ajax_actions.php",
data: "action=search_category_add&title="+$("#category_title").val(),
dataType: "json",
cache: false,
success: function(html)
{
console.log("Category already exists: "+html.category_found);
if(html.category_found == 1)
{
$('#msg_search_load').css({ 'display': 'none' });
$('#msg_search_category').removeAttr('style');
$("#category_title").addClass("already_exists");
}
},
complete: function()
{
// Hide loading
$('#msg_search_load').css({ 'display': 'none' });
}
});
if($("#category_title").hasClass("already_exists")) { return false; }
下面是HTML表单
<form name="add_category" id="add_category" action="<?php echo $s_website_url; ?>/category_add.php" method="post">
<input type="hidden" name="action" value="add_category">
<table cellpadding="4" cellspacing="0">
<tr>
<td width="120">
<label for="category_title">Category title:</label>
</td>
<td>
<div class="content_msg" style="display: none;" id="msg_search_load"><img src="<?php echo $s_website_url; ?>/images/icons/loading.gif" class="content_msg_icon" alt="Warning"> Searching if category already exists.</div>
<div class="content_msg" style="display: none;" id="msg_search_category"><img src="<?php echo $s_website_url; ?>/images/icons/warning.png" class="content_msg_icon" alt="Warning"> Category already exists.</div>
<input type="text" name="category_title" id="category_title" class="form_textfield">
`<div class="content_count_chars" id="count_category_title"><span class="content_count_chars_green">100</span> characters remaining</div>
</td>
</tr>
</table>
<div align="center">
<!-- Fix Opera input focus bug -->
<input type="submit" value="Submit" style="display: none;" id="WorkaroundForOperaInputFocusBorderBug">
<!-- Fix Opera input focus bug -->
<input type="submit" value="Submit" class="form_submit">
</div>
</form>
在AJAX使用的PHP代码:
// If category already exists
if(isset($_GET['action']) && $_GET['action'] == 'search_category_add')
{
$search_category = mysql_query("SELECT `id` FROM `categories` WHERE `title` = '".clear_tags($_GET['title'])."'",$db) or die(mysql_error());
if(mysql_num_rows($search_category) != 0)
{
echo json_encode(array('category_found' => '1'));
}
else
{
echo json_encode(array('category_found' => '0'));
}
}
什么呢'的console.log(HTML)'说明了什么?你有没有证实服务器端脚本工作正常? – 2013-03-08 16:52:02
如果你在'success'函数内执行'console.log(html.toSource())',你会得到什么? – EmCo 2013-03-08 16:54:43
@MarcB'console.log(html)'显示给我'[object Object]' 服务器端脚本没有错误。 – sorinu26 2013-03-08 17:31:54