Javascript jQuery ajax() 在成功时将 json 对象返回给另一个函数会导致错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2512612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery ajax() returning json object to another function on success causes error
提问by Michael Mao
I got stuck in this problem for an hour. I am thinking this is something relates to variable scoping ? Anyway, here is the code :
我被这个问题困了一个小时。我在想这与变量范围有关吗?无论如何,这是代码:
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);
});
}
});
}
}
The for each section works just fine inside the success callback region. I can see Firebug console outputs the route ids with no problem at all.
for each 部分在成功回调区域内工作得很好。我可以看到 Firebug 控制台毫无问题地输出路由 ID。
For decoupling purpose, I reckon it would be better to just return the data object, which in JSON format, to a variable in the caller function, like this:
出于解耦的目的,我认为最好将数据对象以 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);
}
}
});
}
Then all of a sudden, everything stops working! Firebug console reports data object as "undefined"... hasn't that being assigned by the returning object from the method loadRoutes(cityname)?
然后突然之间,一切都停止了!Firebug 控制台将数据对象报告为“未定义”......这不是由方法 loadRoutes(cityname) 的返回对象分配的吗?
Sorry my overall knowledge on javascript is quite limited, so now I am just like a "copycat" to work on my code in an amateur way.
抱歉,我对 javascript 的整体了解非常有限,所以现在我就像一个“模仿者”以业余方式处理我的代码。
Edited : Having seen Nick's hint, let me work on it now and see how it goes.
编辑:看到尼克的提示后,让我现在处理它,看看它是如何进行的。
Edited 2nd :
编辑第二:
bear with me, still stuck in this:
忍受我,仍然停留在这个:
//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 console prints out something interesting :
Firebug 控制台打印出一些有趣的东西:
nowhere
from city found : Sydney
I thought the order should be at least reversed like this :
我认为顺序至少应该像这样颠倒:
from city found : Sydney
nowhere
So, basically, the variable defined in success region has a completely different scope from the same variable outside? This sounds bizarre to me at first but now I see it.
那么,基本上,成功区域中定义的变量与外部相同的变量具有完全不同的作用域?起初这对我来说听起来很奇怪,但现在我明白了。
Still, don't know how to pass the json object out of the success callback to assign it to another variable...
仍然,不知道如何将 json 对象从成功回调中传递出来以将其分配给另一个变量......
Conclusion : okay, I got it, working on "pass by reference" to make use of side-effect to change a variable passed in by function parameter now... Which is not directly related to this question.
结论:好的,我明白了,正在研究“通过引用传递”以利用副作用来更改现在通过函数参数传入的变量......这与这个问题没有直接关系。
回答by Nick Craver
The successcallback occurs when the ajax call completes, so nothing is actually returned by your function, because that statement doesn't run until later.
该success所以没有什么实际上是由你的函数返回,原因是该语句不运行,直到后来出现回调Ajax调用完成时。
In the AJAX scenario, you need to get the data object, then call what should run next, because any successor completecallback functions will happen after the code you're running, when the response from the server comes back.
在 AJAX 场景中,您需要获取数据对象,然后调用接下来应该运行的内容,因为当服务器的响应返回时,任何success或complete回调函数都会在您运行的代码之后发生。
回答by Anthony Walsh
You could maybe try this method:
你或许可以试试这个方法:
function loadRoutes(parameters)
{
return $.ajax({
type: "GET",
async: false, // This is important... please see ref below
// Other Settings (don't forget the trailing comma after last setting)
success: function () {
console.log('Success');
},
error: function () {
console.log('Error');
}
}).responseText;
}
So basically, '.responseText' is added to the '$.ajax' request and the request itself then becomes the return value.
所以基本上,'.responseText' 被添加到 '$.ajax' 请求中,然后请求本身成为返回值。
Please note: This usage - returning the result of the call into a variable - requires a synchronous (blocking) request. So use 'async:false' in the settings.
请注意:此用法 - 将调用结果返回到变量中 - 需要同步(阻塞)请求。所以在设置中使用'async:false'。
To return a JSON value you could use:
要返回 JSON 值,您可以使用:
return $.parseJSON($.ajax({
// Other settings here...
}).responseText);
For more info see: http://api.jquery.com/jQuery.ajax.
有关更多信息,请参阅: http://api.jquery.com/jQuery.ajax。
回答by BenB
Might be a "data" scope problem.
可能是“数据”范围问题。
In the second example, which data is which the json object returned, and which one is the one sent?
在第二个例子中,哪些数据是json对象返回的,哪些是发送的?

