Loading dynamic div content with jQuery from a URL
I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. However, when you either reload the page, click a result which goes to a different page or return back from a previous pa开发者_如何学Cge the search results are no longer there. Why could this be and how can I solve this issue? I do not want to use any plug-ins either.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#type_search').click();
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
When you reload the page, the reason that the results are missing is because they aren't in the document source; they've been added to the DOM later.
I reckon you have two choices, the first of which I generally use.
When you execute your search, have either the search criteria or the search results stored at the server so that when the page is next rendered, the results are rendered with it. I use ASP.NET MVC 3 and do this using a PartialView. When I use jQuery to execute the search, it causes the server to render the same PartialView and inserts the resulting HTML fragment into the results div.
Alternatively, you need to fire your jQuery search again when the page is reloaded.
Whether it's better to resubmit the search or to cache the results depends on how expensive the search is and how big the result set is likely to be.
The hash should stay after the reload of the page because it is part of the browser history.
So you can parse document.location.hash
to gain knowledge about the selected query type and search.
//$(function() {
if(document.location.hash) {
var hash = document.location.hash;
var split = hash.split('/');
var queryType = hash[1];
var searchTerm = hash[2];
$('#type_'+queryType).addClass('selected');
$('#query').text(searchTerm);
$('#query').keyup();
}
//});
behind your setup routines.
精彩评论