开发者

Getting Loads of Unwanted GET Requests with jQuery Ajax

Here's a demo of the work I have at the moment: http://isaaclean.com/test/test2

Basically if you click on "Blog" in the main navigation column, a second column next to it will Ajax loads "blog.html" that contains a list of "posts." If you click on one of the posts in the second column, a third column will load in with the content of the post.

While that's working fine, if you click "Blog" again, this is where the script goes haywire. Firebug shows over 20 GET requests on the second column. And then when you click on a link in the second column after that, an equal amount of GET requests is sent. You can even see the animations going crazy. I have no idea why this is happening.

It started to occur when I added the following lines to mainnav.js:

if($('#listnav').children().size() == 1) {
        $('#listnav nav li').stop().hide("slide", {direction: "left"}, loadContent);
    } else {
        $('#listnav').load(toLoad, '', showNewContent);
    }

The reason why I added this was because I wanted to show the full slide out animation before the script Ajax loads another blog.html when "Blog" is clicked for the second time. Before I implemented the code above and loadContent function, the problem was that the slide out animation was cut off by the loading of the page. To prevent this, I thought using a callback function would work since callbacks occur after the animation is completed.

The only issue with this is that if you first load the page #listnav has no child elements. Therefore if you try using the following code:

$('#listnav nav li').stop().hide("slide", {direction: "left"}, loadContent);

...the callback function is never executed since there are no nav li elements until you click "Blog." That's why I tried开发者_高级运维 to implement an if statement which checks if there are elements within #listnav, and it works fine on the first click, but any clicks after the script just bugs out.

So can anyone help me find a solution to this issue?


I believe your issue is that loadcontent() in mainnav.js is run once for EVERY node it animates. I'm not exactly how the effect you see really ends up happening, but that surely is the root cause.

I can't test this currently so this is untested, but something along these lines should work:

$('#listnav nav li').stop().hide("slide", {direction: "left"});
$('#listnav nav li').last().hide(0, loadcontent);

Note that loadcontent is no longer part of the initial animation but is only executed once the last node is hidden... although, I'm unsure if this code actually works as I can't find way to simply queue a custom function. jQuery effects is not my cup of tea.

But when I think about it, perhaps this is simply a better and more robust solution:

function loadContent() {
    if ($('#listnav nav li:visible').length == 0) {
        $('#listnav').load(toLoad, '', showNewContent);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜