【问题标题】:jQuery - AJAX form validationjQuery - AJAX 表单验证
【发布时间】:2013-03-08 16:48:09
【问题描述】:

我是 jQuery 新手,我尝试验证表单。如果标题已经在数据库中,我想用 ajax 和 php 搜索。我编写的以下代码有效,如果标题已经在数据库中,则返回 1,否则返回 0。在此之后,我想向标题文本字段添加一个类。最后我搜索标题文本字段是否有该类,如果为真则停止表单,否则提交。

即使 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) 显示什么?您是否验证了服务器端脚本工作正常?
  • 如果你在success 函数中执行console.log(html.toSource()),你会得到什么?
  • @MarcB console.log(html) 显示[object Object] 服务器端脚本没有错误。
  • 你在哪里处理表单提交事件
  • 您可能在表单中有一个提交按钮,而提交事件没有错误返回,并且您可能已将点击处理程序附加到此函数。这个函数绑定了什么?一个按钮?任何形式的事件?发布您的表单代码。

标签: php jquery ajax forms validation


【解决方案1】:

我解决了这个问题。我必须将async: false 添加到 AJAX 设置中。

AJAX 是异步的,这基本上意味着它不会阻塞 脚本的执行(这很好,因为您的网站没有 加载时冻结)。

现在的工作代码如下所示:

$.ajax({
       url: "ajax_actions.php",
       type: "GET",
       data: { action: "search_category_add", title: $("#category_title").val() },
       dataType: "json",
       async: false,
       success: function(result)
       {
            // console.log("Category already exists: "+result.category_found);

            if(result.category_found == 1) 
            {
                // console.log("Category already exists: Inside if");

                $('#msg_search_category').removeAttr('style');

                validationErrors++;
            }
        }
});





if(validationErrors > 0) { return false; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多