我正在通过 ajax 发送请求以将数据插入数据库。成功提交后我的按钮消息没有改变。按下时我触发消息 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()
得到一些结果。
最佳答案
this
在 ajax 函数回调中是....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");
},
关于javascript - jquery ajax不执行成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34796471/