【问题标题】:jQuery .submit() success or failure triggerjQuery .submit() 成功或失败触发器
【发布时间】:2011-11-11 04:28:36
【问题描述】:

我正在使用.submit() 定期通过 ajax 提交我的表单,但我希望用户看到表单正在使用旋转轮保存,然后“已保存!”成功后。 jQuery 中有.submit()success 触发器吗?

谢谢!

【问题讨论】:

    标签: javascript jquery ruby-on-rails


    【解决方案1】:

    试试这个:

    jQuery:

    $(document).ready(function() {
        $('#form').submit(function() {
            var status = '<img class="loading" src="loading_detail.gif" alt="Loading..." />';
            $("#ajax").after(status);
            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: $(this).serialize(),
                dataType: 'json',
                success: function(json) {
                    if(json.type == 'success') {
                        $('#msg').css("color","green").html(json.message);
                    } else if(json.type == 'warning'){
                        $('#msg').css("color","yellow").html(json.message);
                    } else if(json.type == 'error'){
                        $('#msg').css("color","red").html(json.message);
                    }
                    $('.loading').remove();
                }
            })
            return false;
        });
    });
    

    HTML:

    <div id="msg"></div>
    <form id="form" method="post" action="action.php" >
        <input type="text" name="email" />
        <input type="submit" name="submit" value="submit" /><span id="ajax"></span>
    </form>
    

    action.php:

    <?php
    if(isset($_POST['email'])){
    $val = $_POST['email'];
    switch ($val) {
        case 'email@site.com':
            $return = array('type'=>'success', 'message'=>'This is success message!'); break;
        case 'email':
            $return = array('type'=>'warning', 'message'=>'This is warning message!'); break;
        default:
            $return = array('type'=>'error', 'message'=>'This is error message!');
    }
    echo json_encode($return);
    }
    ?>
    

    注意: 如果您以编程方式提交表单,则需要再次调用 $('#form').submit(),但这次不带参数,以便触发提交事件。

    【讨论】:

    • 你答案的something 部分让我感到困惑。
    【解决方案2】:

    您可以使用手动 $.post() 请求而不是 .submit()$.post() 有一个成功回调。

    您必须填写 $.post()(目标 URL)和 .serialize() 表单元素的详细信息。

    【讨论】:

      【解决方案3】:

      要在提交页面时显示一个旋转的轮子,请尝试获取一个动画 GIF(有很多免费的加载圆圈)。此 GIF 在您的页面中实现:

      class="myloadingcircle" style="display:none"
      

      然后使用jQuery:

      $("form").submit(function(e) { $(".myloadingcircle").show(); });
      

      【讨论】:

      • 如果与表单验证配对,这将不起作用。即使表格无效,纺车也会发光。
      猜你喜欢
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 2023-04-04
      • 2020-11-11
      • 2011-08-05
      • 1970-01-01
      相关资源
      最近更新 更多