Jquery AJAX:如何在"成功"上更改按钮值?

Aak*_*oel 6 ajax jquery

我在一个页面上有多个按钮.点击后,我跟踪按钮ID,发送按钮值到后端php代码,通过更改数据库返回更新的值.除了这个,我能够得到我需要的一切:成功时设置按钮值!这是我正在使用的代码:

$(document).ready(function(){
    $("input[type='button']").click(function(){
        var selected = $(this).attr("id");
        var val = prompt("Enter new value",0);
                    $.ajax({
                    url:'updateCostItems.php',
                    data:{toupdate:selected, updatewith:val},
                    type:'GET',
                    dataType:'json',
                    success:function(json){
                        $(this).val(json.update);
                    },
                    error:function(xhr, status){
                        alert("Problem");
                    },
                    complete:function(xhr, status){

                    }
                });
        });
});
Run Code Online (Sandbox Code Playgroud)

Bil*_*oon 4

我认为this这是不正确的,因为回调是在全局范围内运行的。

$.ajax未经测试,但在编写之前尝试var $this = $(this),然后在回调中使用$this.val(json.update)


编辑:更新了代码片段以$this通过使用 var 声明来确保本地。其他帖子建议var button = $(this)在较大的项目中使用 which 可能更好,因为跟踪变量更具挑战性 - 但所有答案实际上都是相同的。