I'm confused about the .load()
and $.ajax
. I have the following jQuery code in my index.html
:
$('.load_ext').click(function(e) {
var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load').html('<p class="loading">Loading…</p>').hide().fadeIn('slow'));
})
and HTML:
<a href="test.html" class="load_ext">test</a>
In the example above, I'm loading partial content from the test.html
(the content of id #content_to_load
). I also want to grab the title of that test.html
page and replace the index.html
title page with that one.
I tried doing something like:
var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load', function() {
console.log($(document).attr('title'));
}).html('<p class="loading">Loading…</p>').hide().fadeIn('slow'));
without any luck. It gives me the current page title. How can I replace the title by doing something like:
$('title').text(newPageTitle);
Thanks!
EDIT: Thanks to @Jeff Schafer, @dystroy, and @zeroflagL I managed to solve this problem. Here's the changed code:
var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load', function(responseText) {
var title = responseText.match(/<title>([^<]*)/)[1];
document.title = title;
}).html('<p class="loading">Loading…</p>').hide().fadeIn('slow'));
The main problem with load
is that jQuery, when building the DOM fragment, strippes what isn't the body. You can use this to get the title of a distant page :
$.get(url, function(html){
var matches = html.match(/<title>([^<]*)/);
if (matches.length>0) {
var title = matches[1];
document.title = title;
}
});
Note that this won't work if the distant page is from a different origin and doesn't specifically allow cross-domain requests.
You can get the title of the new page through the responseText:
.load(url + ' #content_to_load', function(responseText) {
repsonseText
is literally text, though, the source code of the page. You can use regular expressions, for instance, to extract the title of test.html
. Then you can change the title with document.title = newTitle
.
try this code to change page title
document.title = newPageTitle;
hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.