访问 $.post jQuery 中的变量

Accessing a variable inside $.post jQuery

本文关键字:变量 jQuery post 访问      更新时间:2023-09-26

我有一个调用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 + '">');
    }
  }
});