我正在构建一个基于 ajax 的导航,一切正常,除了一件事:
当我查看 Firebug 时,我可以看到每次点击时 ajax 站点都会被调用并加载两次。
这是脚本:
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the main and show the progress bar
$('#main').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
//AJAX Navigation Helper function
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
//AJAX Navigation Helper function
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the main retrieved from ajax and put it in the #main div
$('#main').html(html);
//display the body with fadeIn transition
$('#main').fadeIn('slow');
//reload site scripts
$.getScript("js/script.js");
}
});
}
因此,每当我单击导航中的列表时,页面都会很好地加载到 #main 中,但它会发生两次(如 Firebug 中所示)。 Any1 也许知道为什么吗? :)
我注意到当我通过 url 访问某个页面时不会发生这种情况(比它只执行一次 ajax 调用),所以我猜问题出在 click 函数中的某个地方。
附:我正在使用jquery历史记录插件,但我不认为问题在那里,或者?
最佳答案
我猜测 getPage 被调用了两次。在函数的开头放一条调试器语句(debugger;)并打开firebug看看是否是。如果调用两次,这是解决问题的一种方法:
//AJAX Navigation Helper function
function getPage() {
if(getPage.isLoaded != true) {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the main retrieved from ajax and put it in the #main div
$('#main').html(html);
//display the body with fadeIn transition
$('#main').fadeIn('slow');
//reload site scripts
$.getScript("js/script.js");
}
});
}
getPage.isLoaded = true;
}
关于jquery + AJAX + 双重调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7533666/