我陷入了這個問題一個小時。我在想這與變量範圍有關?總之,這裏是代碼:jQuery ajax()返回json對象成功導致另一個函數導致錯誤
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);
});
}
});
}
的每一部分工作的成功回調區域內就好了。我可以看到Firebug控制檯輸出路徑標識符完全沒有問題。
去耦的目的,我認爲它會更好,只是返回的數據對象,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
因此,基本上,成功區域中定義的變量與外部相同變量具有完全不同的範圍?起初我聽起來很奇怪,但現在我明白了。
不過,不知道如何通過JSON對象了成功回調將其分配給另一個變量...
結論:好吧,我知道了,就到「按引用傳遞」工作利用副作用來改變現在通過函數參數傳入的變量......這與這個問題沒有直接關係。
好點,沒有什麼可以返回... – BenB 2010-03-25 01:41:30
有道理.... – 2010-03-25 01:41:48
@Nick Craver:在調用函數findFromCity(continent,x,y)中將回調節名稱從「success」更改爲「complete」不會解決這個問題。數據仍然被識別爲「未定義」。 – 2010-03-25 01:45:52