我在这个问题上卡了一个小时。我在想这与变量作用域有关吗?无论如何,这是代码:
function loadRoutes(from_city)
{
$.ajax(
{
url: './ajax/loadRoutes.php',
async : true,
cache : false,
timeout : 10000,
type : "POST",
dataType: 'json',
data :
{
"from_city" : from_city
},
error : function(data)
{
console.log('error occured when trying to load routes');
},
success : function(data)
{
console.log('routes loaded successfully.');
$('#upperright').html(""); //reset upperright box to display nothing.
return data; //this line ruins all
//this section works just fine.
$.each(data.feedback, function(i, route)
{
console.log("route no. :" + i + " to_city : " + route.to_city + " price :" + route.price);
doSomethingHere(i);
});
}
});
for each 部分在成功回调区域内工作得很好。我可以看到 Firebug 控制台毫无问题地输出路由 ID。
出于解耦的目的,我认为将 JSON 格式的数据对象返回给调用函数中的变量会更好,如下所示:
//ajax load function
function findFromCity(continent, x, y)
{
console.log("clicked on " + continent + ' ' + x + ',' + y);
$.ajax(
{
url: './ajax/findFromCity.php',
async : true,
cache : false,
timeout : 10000,
type : "POST",
dataType : 'json',
data :
{
"continent" : continent,
"x" : x,
"y" : y
},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
var cityname = data.from_city;
//only query database if cityname was found
if(cityname != 'undefined' && cityname != 'nowhere')
{
console.log('from city found : ' + cityname);
data = loadRoutes(cityname);
console.log(data);
}
}
});
}
突然之间,一切都停止了! Firebug 控制台将数据对象报告为“未定义”...不是由方法 loadRoutes(cityname) 的返回对象分配的吗?
抱歉,我对 javascript 的整体知识非常有限,所以现在我就像一个“模仿者”,以业余方式编写我的代码。
已编辑:看到 Nick 的提示后,让我现在开始研究它,看看进展如何。
第二次编辑:
忍受我,仍然停留在这个:
//ajax load function
function findFromCity(continent, x, y)
{
console.log("clicked on " + continent + ' ' + x + ',' + y);
var cityname = "nowhere"; //variable initialized.
$.ajax(
{
url: './ajax/findFromCity.php',
async : true,
cache : false,
timeout : 10000,
type : "POST",
dataType : 'json',
data :
{
"continent" : continent,
"x" : x,
"y" : y
},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
cityname = data.from_city;
//only query database if cityname was found
if(cityname != 'undefined' && cityname != 'nowhere')
{
console.log('from city found : ' + cityname);
//data = loadRoutes(cityname);
//console.log(data);
}
}
});
return cityname; //return after ajax call finished.
}
Firebug 控制台打印出一些有趣的东西:
nowhere
from city found : Sydney
我认为至少应该像这样颠倒顺序:
from city found : Sydney
nowhere
那么,基本上,success region中定义的变量和外面的同一个变量的作用域是完全不同的吗?起初我觉得这很奇怪,但现在我明白了。
仍然,不知道如何将 json 对象从成功回调中传递出去,以将其分配给另一个变量...
结论:好的,我明白了,正在研究“通过引用传递”以利用副作用来更改函数参数传入的变量……这与这个问题没有直接关系。
最佳答案
success
回调在 ajax 调用完成时发生,因此您的函数实际上没有返回任何内容,因为该语句直到稍后才运行。
在AJAX场景中,你需要获取数据对象,然后调用接下来应该运行的,因为任何success
或complete
回调函数都会在你的代码之后发生'正在运行,当服务器返回响应时。
关于javascript - jQuery ajax() 在成功时将 json 对象返回给另一个函数会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2512612/