我在一个页面上多个按钮。一旦点击,我跟踪按钮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.
相关推荐
最新文章