2013-03-11 128 views
0

我想從另一個頁面使用ajax加載div,但使用歷史API維護URL完整性。 ajax和歷史部分正在工作(即div加載和url正在改變),但由於某種原因,我的div包含我的整個頁面,而不僅僅是在div中意味着什麼!爲什麼我的整個網頁都填充了我的div?

原始頁面和正在加載的頁面div都是這種情況。

剝去HTML

<!DOCTYPE html> 
<html> 
    <body> 
    <div id="slider"> 
     ... all the page content 
     <a rel='tab' href="p/password.jsf">Forgot password?</a> 
    </div> 
    </body> 
</html> 

JS

<script> 
    $(function(){ 
     $("a[rel='tab']").click(function(e){ 

      //get the link location that was clicked 
      pageurl = $(this).attr('href'); 

      //to get the ajax content and display in div with id 'content' 
      $.ajax({ 
       url:pageurl + '?rel=tab', 
       success: function(data){ 
        $('#slider').html(data); 
       }}); 

      //to change the browser URL to 'pageurl' 
      if(pageurl!=window.location){ 
       window.history.pushState({path:pageurl},'',pageurl);  
      } 
      return false; 
     }); 
    }); 

    /* the below code is to override back button to get the ajax content without reload*/ 
    $(window).bind('popstate', function() { 
     $.ajax({ 
      url:location.pathname+'?rel=tab', 
      success: function(data){ 
       $('#slider').html(data); 
      }}); 
    }); 
</script> 
+0

因爲ajax讀取頁面響應(這是整頁)..所以對Ajax的響應是什麼在頁面中排序所見即所得thingy – 2013-03-11 16:39:10

回答

2

您用Ajax響應 然後做recive頁面的特定部分,那麼您可以使用load方法與元素的id來獲取內容。

$('#slider').load(pageurl + '?rel=tab #container_with_content_to_fetch', function() { 
    alert('callback after success.'); 
}); 

更多信息有關load()info

+0

謝謝Sven這正是需要什麼。我怎樣才能達到popstate相同的結果?目前我正在使用'$('#slider')。load(location.pathname);'但是在原始頁面加載中,整個頁面填充了#slider div。我嘗試了'$('#slider')。load(location.pathname +'#slider');'但不喜歡那樣。 – tarka 2013-03-12 09:22:18

+0

沒問題!在'url'和'id'之間需要一個空格:'$('#slider')。load(location.pathname +'#slider');' – 2013-03-12 10:27:00

+0

這已經取消了這個效果,只是將鏈接視爲正常鏈接通過再次加載整個頁面。 – tarka 2013-03-12 10:52:42

0

您可能需要停止默認的點擊動作。看起來您的鏈接看起來像是......鏈接。

$("a[rel='tab']").click(function(e){ 
    e.preventDefault(); 
    ... 
0

你,如果你想如果你想獲取使用Ajax的網頁的一部分,選擇以下

/* the below code is to override back button to get the ajax content without reload*/ 
    $(window).bind('popstate', function() { 
     $.ajax({ 
      url:location.pathname+'?rel=tab', 
      success: function(data){ 
       var mydiv = $('#my_div_id' , data) // this will get the div with an id of #my_div_id 
       $('#slider').html(mydiv); 
      }}); 
    }); 
0

$.ajax加載整個頁面。您可以使用​​

而不是

$.ajax({ url:pageurl + '?rel=tab', success: function(data){ $('#slider').html(data); }});

可以使用

$('#slider').load(pageurl + ' [rel=tab]');

的文檔是here

相關問題