Jquery ajax没有执行成功

时间:2016-01-14 17:54:52

标签: javascript jquery html ajax dom

由ajax发送请求以在数据库中插入数据。提交成功后,我的按钮消息没有改变。在触发成功时按i消息Please wait...设置新的html值Done。数据库中的记录已成功创建,但Done的按钮文本未更改。

我的剧本:

var Friend = {

    // Add new friend
    add: function() {
        var btn = $(".btn-add-friend");

        btn.click(function() {

            $(this).html("Please wait...");

            $.ajax({
                type: "post",
                url: baseurl + "/FriendRequest/send",
                data: {
                    friend: $(this).data('friend')
                },

                success: function(xhr, status) {
                    $(this).html("Done"); // Not wortk

                    alert("done"); // <-- Work 
                },
                error: function(response, s, e) {
                    alert(response.responseText);
                },
                complete: function () {
                     //. the some from success
                }
            });
        });
      },

    // Initialise
    init: function() {
        Friend.add();
    }
};

HTML:

<button type="button" id="item-<?=$person->account_id;?>" class="btn  btn-xs btn-add-friend has-spinner" data-friend="<?= $person->account_id;?>"><i class="fa fa-plus-circle"></i> Add Friend</button>

当我点击按钮时,文本被更改为Please wait..但成功后未更改为Done并且警报成功执行。

点击后看起来它不是DOM的一部分!另外,我尝试使用on()得到的结果。

3 个答案:

答案 0 :(得分:4)

ajax函数回调中的

this是.... ajax调用,而不是被点击的元素。
你必须用它替换它

add: function() {
    var btn = $(".btn-add-friend");

    btn.click(function() {

        var self = $(this);

        self.html("Please wait...");

        $.ajax({
            type: "post",
            url: baseurl + "/FriendRequest/send",
            data: {
                friend: self.data('friend')
            },
            success: function(xhr, status) {
                self.html("Done");
            },

答案 1 :(得分:1)

要使用this,您需要其他属性。使用url

添加以下内容
context:this

因此,更新的代码将是

$.ajax({
            type: "post",
            url: baseurl + "/FriendRequest/send",
            context:this,
            data: {
                friend: $(this).data('friend')
            },

            success: function(xhr, status) {
                $(this).html("Done"); // Will work

                alert("done"); // <-- Work 
            },
            error: function(response, s, e) {
                alert(response.responseText);
            },
            complete: function () {
                 //. the some from success
            }
        });

答案 2 :(得分:1)

在回调中,这是指Ajax调用的jqXHR对象,而不是元素。所以尝试在ajax请求之前将它分配给变量,然后在成功函数中使用这个变量:

//Before ajax request
var _this = $(this);

//Inside success function
_this.html("Done");

希望这有帮助。

相关问题