在页面重新加载后加载动态生成的内容和URL

时间:2011-06-09 20:58:30

标签: javascript jquery html

我有一个用jQuery编写的Google Instant样式搜索脚本。当用户搜索时,会创建一个类似#search / QUERY / 3 /的URL。但是,当您重新加载页面时,单击转到其他页面的结果或从上一页返回的搜索结果不再存在。为什么会这样?

这是我的jQuery代码:

$(document).ready(function(){
    $("#search").keyup(function(){
        var search=$(this).val();
        var query=encodeURIComponent(search);
        var page=1;
        var yt_url='search.php?q='+query+'&category=web&d='+page+'';
        window.location.hash='search/'+query+'/'+page+'/';
        document.title=$(this).val()+" - My Search Script";
        if(search==''){
            window.location.hash='';
            document.title='My Search Script';
        }
        $.ajax({
            type:"GET",
            url:yt_url,
            dataType:"html",
            success:function(response){
                if(response !=""){
                $("#result").html(response);
                } else {
                $("#result").html("Your search did not return any results");
                }
            }
        });
    });
if(window.location.hash.indexOf('#search/')==0){
    query=window.location.hash.replace('#search/', '').replace('/1/', '');
    $('#search').val(decodeURIComponent(query)).keyup();
}
});

我认为这可能与这些代码行有关:

if(window.location.hash.indexOf('#search/')==0){
    query=window.location.hash.replace('#search/', '').replace('/1/', '');
    $('#search').val(decodeURIComponent(query)).keyup();
}

1 个答案:

答案 0 :(得分:0)

您需要为搜索编写一个函数,以便指定页码。

$(document).ready(function(){
  var search = function (query, page) {
    page = page ? page : 1;
    query = encodeURIComponent(query),
    var yt_url = 'search.php?q=' + query + '&category=web&d=' + page + '';
    if (query == '') {
        window.location.hash = '';
        document.title = 'My Search Script';
    } else {
      window.location.hash = 'search/' + query + '/' + page + '/';
      document.title = $(this).val() + " - My Search Script";
    }
    $.ajax({ ... });
  };

  $("#search").keyup(function(){ search(this.value); });

  if (window.location.hash.indexOf('#search/') == 0) {
    var query = window.location.hash.replace('#search/', ''),
      page = query.replace(/.+?\/(\d+)\//, '$1');
    query = query.replace(/\/\d+\//, '');
    search(decodeURIComponent(query), page);
  }
});