我试图在我的ajax响应中访问变量'dimensions'但是无法获得它.我不想让这个变量全局化.以下是我的代码
$(document).ready(function(){
$('#submittext').click(function(){
var dimensions;
$.ajax({
type: "GET",
url: "bin/getcontentsize.php",
data: findContentsize,
success: function(response){
//want to access dimensions here to assign response and some calculation(but not able to access it)
}
});
//so i can use here
});
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以dimensions在启动ajax请求后立即从ajax回调和代码中访问变量.可以在这两种上下文中访问该变量.
最有可能导致问题的是时机.success在ajax请求完成后,该方法将异步运行.最好将此视为稍后执行.但是,紧接着$.ajax调用后的代码将立即执行.因此success,当dimensions变量运行时,您将看不到处理程序对变量的任何影响.
如果您希望使用方法dimensions计算的值运行success代码,则需要从success回调中调用该代码.例如
$('#submittext').click(function(){
var handleNewDimensions = function (dimensions) {
// Code that used to be after the $.ajax line
}
$.ajax({
type: "GET",
url: "bin/getcontentsize.php",
data: findContentsize,
success: function(response){
var dimensions = doTheCalculation(...);
// Call the code which needs to deal with the new dimensions
handleNewDimensions(dimensions);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |