jQuery AJAXメソッドでデータを取得する2つの関数があります。jQueryを含む関数ajaxがデータを返さない
どちらもURLと同じに見えます。両方の要求は成功し、コンソールにデータを表示しますが、親関数を介してデータを返すのは1つだけです。
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)
});