使用ajax之外的变量
如何从ajax中使用count变量?在ajax函数中,“count”显示count,但不显示任何内容使用ajax之外的变量,ajax,function,Ajax,Function,如何从ajax中使用count变量?在ajax函数中,“count”显示count,但不显示任何内容 var count; $.ajax({ cache : false, dataType: 'json', type : "POST", url : "count.php", success : function(tdata){ count = tdata; console.log(count); //this works }
var count;
$.ajax({
cache : false,
dataType: 'json',
type : "POST",
url : "count.php",
success : function(tdata){
count = tdata;
console.log(count); //this works
}
});
console.log(count); //this doesn't work
$.ajax()
是异步的,您需要等待它完成
var count;
$.ajax({
cache : false,
dataType: 'json',
type : "POST",
url : "count.php",
success : function(tdata){
count = tdata;
console.log(count); //this works
}
})
.done(() => {
// this code runs after ajax is resolved
console.log(count);
});
有关其他链接方法的信息,请参阅您认为它不起作用是什么意思?它是否说“未定义”?您的ajax调用是异步的,因此您的控制台日志在响应前会打印出来,您可以使其同步,但这不是一个好的做法。您可以使用回调函数进行可能的重复。在ajax中成功执行任何您想要执行的操作,但我有大量代码!我可以;t put.done(()=>{});代码的大小并不重要。此外,根据您的环境,您可以尝试使用async/await。