我有2個功能,其經由jQuery的AJAX方法獲取數據。功能包括jQuery的AJAX不返回數據
這兩個看起來都一樣,除了URL。這兩個請求都成功,並顯示在控制檯中的數據,但只有一個通過父函數返回的數據。
saveLoc取,說「OK」數據,以及「OK」,如果是印在父代碼來安慰返回。 getLoc獲取數字,例如「17」。數被打印從函數內到控制檯,但在父代碼中,變量(savedLoc)簡單地返回未定義
任何意見?我錯過了什麼嗎?
function saveLoc(story,chapter,loc) {
\t jQuery.ajax({
\t \t \t \t \t \t type: "GET",
\t \t \t \t \t \t url: "index.php?action=saveloc&story="+story+"&chapter="+chapter+"&loc="+loc,
\t \t \t \t \t \t data: "",
\t \t \t \t \t \t cache: false,
\t \t \t \t \t \t success: function (data2) {
\t \t \t \t \t \t \t \t console.log("Location saved: "+loc);
\t \t \t \t \t \t \t \t return data2;
\t \t \t \t \t \t }
\t \t \t \t });
}
function getLoc(story,chapter) {
\t jQuery.ajax({
\t \t \t \t \t \t type: "GET",
\t \t \t \t \t \t url: "index.php?action=getloc&story="+story+"&chapter="+chapter,
\t \t \t \t \t \t data: "",
\t \t \t \t \t \t cache: false,
\t \t \t \t \t \t success: function (data) {
\t \t \t \t \t \t \t \t console.log("Location retrieved: "+data);
\t \t \t \t \t \t \t \t return data;
\t \t \t \t \t \t }
\t \t \t \t });
}
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var story = $.urlParam('story');
var chapter = $.urlParam('chapter');
$(document).ready(function(){
\t var start = 1;
\t var savedLoc = getLoc(story,chapter);
\t
\t console.log("savedLoc: "+savedLoc);
\t if(savedLoc > 0) {
\t \t var d = $(document).height(),
\t \t \t c = $(window).height();
\t \t var scrollPos = Math.floor((savedLoc/100) * (d - c));
\t \t window.scrollTo(0, scrollPos);
\t }
\t setTimeout(function() {
\t \t $(window).on('scroll', function(){
\t \t \t console.log("scroll detected");
\t \t \t setTimeout(function() {
\t \t \t \t var s = $(window).scrollTop(),
\t \t \t \t \t d = $(document).height(),
\t \t \t \t \t c = $(window).height();
\t \t \t \t var scrollPercent = (s/d) * 100;
\t \t \t \t saveLoc(story,chapter,scrollPercent);
\t \t \t },3000);
\t \t });
\t },6000)
});