jQuery/AJAX - How to load multiple divs and page title?
I tried this code (it works but when we click 3-4 times, my browser frezzes, maybe due to huge variables):
var elements = [ "content", "menu" ];
$.get(
url,
function(data)
{
// Elements
var resp = $("<div></div>").html(data);
$.each(
elements,
function(i, v)
{
var content = resp.find("#"+v);
$("#"+v).html(content);
}
);
// Title
开发者_运维技巧 var regexp = /<title>(.*)<\/title>/i;
document.title = data.match(regexp)[1];
// Change URL
history.pushState({ page: url }, url, url);
// Hiding loading div
}
);
Tested on Firefox 6.0, Chrome, and Safari 5...
I think I may use the .load() function, but I can't load multiple divs with only one load...
And the following code isn't working:
var resp = $("<div></div>").load(url+" #content, #menu");
var content = resp.find("#content");
$("#content").html(content);
var menu = resp.find("#menu");
$("#menu").html(menu);
Thank you for your help!
turn the cache on
$.ajaxSetup({
cache: true,
});
rest of the code as it is
var elements = [ "content", "menu" ];
$.get(
url,
function(data)
{
// Elements
var resp = $("<div></div>").html(data);
$.each(
elements,
function(i, v)
{
var content = resp.find("#"+v);
$("#"+v).html(content);
}
);
// Title
var regexp = /<title>(.*)<\/title>/i;
document.title = data.match(regexp)[1];
// Change URL
history.pushState({ page: url }, url, url);
// Hiding loading div
}
);
I found a clue to resolve my problem...
By adding a 'time()' (PHP function) in the #menu div, I noticed that sometimes, jQuery loads the page several times without any reason : this is why my browser is laggy during loadings...
Does someone have any idea about how to fix this problem?
Thank you.
EDIT : I think I fixed my problem! I don't lock this question until I'm sure about that :)
The problem was the use of multiple IDs like :
<div id="content">
<div id="content">
</div>
</div>
When I loaded my content. So now, the code is :
$.get(
url,
function(data)
{
// Elements
//var resp = $("<div></div>").html(data); <-- EDIT
var resp = $(data);
$.each(
elements,
function(i, v)
{
var content = resp.find("#"+v).html(); // HERE IS THE CHANGE, I ADDED .html()
$("#"+v).html(content);
}
);
// Title
var regexp = /<title>(.*)<\/title>/i;
document.title = data.match(regexp)[1];
// Change URL
history.pushState({ page: url }, url, url);
// Hiding loading div
}
);
精彩评论