[英]jQuery AJAX Request Doesn't Work on Page Load, However, It Does Work from Debug Console
在jQuery中關閉異步請求解決了該問題。
我的頁面中有以下Javascript和AJAX請求(使用jQuery):
"use strict";
var hsArea, counter, hotspots, count;
counter = 4;
count = 0;
hotspots = {};
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
});
}
function displayHotspot(type, id, number) {
$.ajax({
url: '/alpha/engine/hotspots/gethotspot.php',
dataType: 'json',
data: {'type' : type, 'id' : id},
success: function(json) {
console.log(json);
var hotspot, extract;
extract = json.content;
extract = extract.replace(/<(?:.|\n)*?>/gm, '');
extract = extract.substring(0, 97);
extract = extract + "...";
json.content = extract;
hotspot = document.createElement("div");
hsArea.append(hotspot);
hotspot.setAttribute('class','hotspot');
hotspot.setAttribute('id','hotspot' + number);
$(hotspot).css('position', 'absolute');
$(hotspot).css('top', number * 100 + 100);
$(hotspot).css('left', number * 100 + 110);
hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
}
function listHotspots() {
for(count = 0; count < counter; count++) {
(function(count) {
displayHotspot('scribble',hotspots[count], count);
count = count + 1;
})(count);
}
}
function loadHotspots() {
fetchHotspotList();
listHotspots();
}
$(document).ready(function() {
hsArea = $("#hotspotArea");
fetchHotspotList();
listHotspots();
});
(抱歉,格式設置有點過關!)-現在,$(document).ready()函數將hsArea變量分配為應有的值,但是fetchHotspotList()和listHotspots()的組合返回:
Uncaught TypeError: Cannot call method 'replace' of null
但是,如果在Google Chrome Javascript控制台中運行:
loadHotspots();
它從AJAX請求中獲取數據,並在頁面上正確顯示。 起初我以為問題是我沒有使用$(document).ready()處理程序,但是添加它並沒有解決它。 兩者都沒有在body標簽內部使用onload處理程序。
任何幫助將不勝感激。
問候,本。
可能是由於在fetchHotSpots
返回之前調用了listHotSpots
函數(因為它是一個異步調用)。
最好將listHotSpots
的執行與listHotSpots
的完成聯系fetchHotSpots
,如下所示:
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
listHotSpots();
});
}
您最好修改listHotSpots
以獲取從AJAX調用返回的json數據。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.