2013-03-11 118 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

相关问题