【问题标题】:Change text of button on ajax success callback更改 ajax 成功回调按钮的文本
【发布时间】:2014-06-05 04:46:49
【问题描述】:

我一直在努力更改触发我的 ajax 请求以显示数据已成功发送到服务器的按钮文本。

标记

使用 laravel,我有这种形式:

{{ Form::open(array('url' => 'panel/update/user', 'style' => 'display:inline', 'id' => 'ajax')) }}

    {{ Form::hidden('action', 'confirm') }}
    {{ Form::hidden('user', $confirmed->username) }}

      <button class="btn-xs btn-default pull-right btn" style="padding: 1px 5px;" type="submit" data-after="User Confirmed">Confirm User</button>

{{ Form::close() }}

对于 javascript:

$('form#ajax').on('submit', function(){
    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {};

    that.find('[name]').each(function(index, value){
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response){

            $('#console p').text(response); // This is logging the response from the server in a little console I built.



            /*
            | If data-after is set, then set the value to the button that triggered this 
            */


            if(this.attr('data-after').length) {

                console.log(this);

            }



        }
    });

    return false;
});

ID 为#ajax 的任何表单都将使用ajax 提交。我现在正在尝试实现一种方法来指定一些数据属性以向触发提交以显示表单已提交的当前按钮显示文本。所以data-after="Submitted" 将在成功时将文本从Confirm => Submitted 更改。我想要这个表格,而不是全部改变。

问题

这是不是我在页面上的唯一表单。目的是从数据库中获取未确认的用户,然后通过单击通过 ajax 将数据发送到服务器的按钮来确认他们。数据发送后,我想将按钮中的文字改为data-after中指定的文字。我有多个带有 multiple data-after 的表单,所以我不想更改所有按钮。这就是我卡住的地方。我想表明表单已提交。

【问题讨论】:

    标签: javascript php jquery ajax forms


    【解决方案1】:

    您可以在提交事件开始时定位按钮,然后在success 方法中引用它。

    缩写示例:

    $('form#ajax').on('submit', function() {
            var $button = $(this).find('button');
    
            $.ajax({
                url: url,
                type: type,
                data: data,
                success: function(response) {
                    // button manipulation here
                    $button.attr('disabled', 'disabled').text('Submitted');
                }
            });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 2023-03-24
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多