jQuery的AJAX:如何在&QUOT更改按钮值;成功"? [英] Jquery AJAX: How to Change button value on "success"?

查看:92
本文介绍了jQuery的AJAX:如何在&QUOT更改按钮值;成功"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个页面上多个按钮。一旦点击,我跟踪按钮ID,按钮值发送到后端PHP code,返回我的更新值通过更改数据库。我能找回我需要的一切,除了这一点:设置成功的按钮值!这是code我使用的:

  $(文件)。就绪(函数(){
    $(输入[类型='按钮'])。点击(函数(){
        VAR选择= $(本).attr(ID);
        VAR VAL =提示(请输入新的价值,0);
                    $阿贾克斯({
                    网址:updateCostItems.php,
                    数据:{更新所使用:选择,updatewith:VAL},
                    键入:GET,
                    数据类型:JSON,
                    成功:函数(JSON){
                        $(本).VAL(json.update);
                    },
                    错误:函数(XHR,状态){
                        警报(问题);
                    },
                    完成:功能(XHR,状态){

                    }
                });
        });
});
 

解决方案

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

未经检验的,但尝试之前 $。阿贾克斯变量$此= $(本),然后在回调使用 $ this.val(json.update)


编辑:更新code段,以确保当地 $这种通过使用var声明。其他职位建议使用 VAR键= $(本)这可能是在更大的项目更好的地方保持变量的轨道是更具挑战性 - 但所有的答案都是一样的真。

I have multiple buttons on one page. Upon click, I track the button id, send the button value to backend php code that returns me updated value by changing the database. I am able to get back everything i need except this: Setting the button value on success!! This is the code i'm using:

$(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){

                    }
                });
        });
});

解决方案

I think this is not correct, because the callback is run in the global scope.

Untested, but try just before $.ajax to write var $this = $(this) and then in your callback use $this.val(json.update)


Edit: Updated code snippet to ensure local $this by declaring with var. Other posts suggest using var button = $(this) which is probably better in bigger projects where keeping track of the variables is more challenging - but all the answers are the same really.

这篇关于jQuery的AJAX:如何在&QUOT更改按钮值;成功"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆