访问 $.post jQuery 中的变量
Accessing a variable inside $.post jQuery
我有一个调用jQuery $.post
函数的事件。我想访问 $.post
函数中的已定义变量,但我遇到了麻烦。
在这种情况下,我想访问currentId
变量。
$('.notMatching').click(function(){
var currentId = this.id;
$.post("http://"+ document.domain + baseUrl +"/tables/demo.json", { id: this.id },
function(dat){
alert(currentId); //undefined
if(dat['result']==1){
$(this).parent().html('<input type="checkbox" class="first" value="'+this.id+'">');
}
}
);
});
有没有办法做到这一点?
顺便说一句,这个事件与许多其他事件一起$(document).ready(function(){
。
你不需要通过做任何全局的事情来做任何赋值......
$('.notMatching').click(function(){
var that = this
$.post("http://"+ document.domain + baseUrl +"/tables/demo.json", { id: this.id },
function(dat){
alert(that.id);
if(dat['result']==1){
$(this).parent().html('<input type="checkbox" class="first" value="'+that.id+'">');
}
}
);
});
将您的this
变量分配给that
,您的变量将在成功回调中访问$.post
请全局声明变量!
var currentId = null;
$('.notMatching').click(function() {
currentId = this.id;
$.post("http://" + document.domain + baseUrl + "/tables/demo.json", {
id : this.id
}, function(dat) {
alert(currentId);
//undefined
if (dat['result'] == 1) {
$(this).parent().html('<input type="checkbox" class="first" value="' + this.id + '">');
}
});
});
回
调内的作用域被更改,需要保留它
$('.notMatching').click(function(){
var currentId = this.id;
var that = this;
if (currentId)
$.post("http://"+ document.domain + baseUrl +"/tables/demo.json", { id: currentId }, function(dat){
if(dat['result']==1)
$(that).parent().html('<input type="checkbox" class="first" value="'+currentId+'">');
});
else
alert('No Id');
});
var currentId = null;
var that = this;
$('.notMatching').click(function() {
currentId = this.id;
$.ajax({
'type' : 'POST',
'dataType' : 'JSON',
'data': {'id':currentId},
'url': "http://" + document.domain + baseUrl + "/tables/demo.json",
'success': function(response){
if ((JSON.parse(response)).result === 1) {
$(this).parent().html('<input type="checkbox" class="first" value="' + that.id + '">');
}
}
});
相关文章:
- 值未传递给变量(JQuery、Javascript)
- 附加要使用的变量jQuery验证插件
- 按钮变量范围 - 如何更新父范围中的变量?jQuery.
- grunt-contrib-jasmine ReferenceError: 找不到变量: jQuery.
- 未定义的变量 jQuery 对象
- 调用变量 jQuery 函数
- 访问正在改变函数内部的变量(jQuery)
- 在变量jquery日期选择器中获取今天的日期和所选日期
- 如何序列化存储在变量 jQuery 中的表单
- 如何在单独的函数中获取此变量?(jQuery)
- 可以't在嵌套函数中使用javascript变量(jquery砖石插件)
- 将.attr()添加到变量Jquery中
- 将.change函数中变量的值传递并更新到全局变量Jquery
- 将ajax变量Jquery到php中
- 用两个双引号和加号包围javascript变量jquery $.post
- 如何将html结构存储在变量jquery中
- 如何通过名称空间变量进入点击函数参数变量?jQuery
- 检查if条件,if语句被赋值为字符串变量- jquery|| javascript
- 从on()函数返回变量- jquery
- 创建一个变量,在每个循环中使用一个变量- jQuery