更改ajax成功回调按钮的文本

Change text of button on ajax success callback

本文关键字:文本 按钮 回调 ajax 成功 更改      更新时间:2023-09-26

我一直在努力更改触发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中指定的文本。我有多个表单与多个数据后的,所以我不想改变所有的按钮。这就是我被卡住的地方。我想显示表单已经提交。

您可以将按钮定位在提交事件的开头,然后在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');
            }
        });
});