2016-02-04 25 views
0

我做了一個Ajax的#container DIV用PHP包括:主頁加載兩個時間onpopstate

<div id="container"> 
 
\t <?php 
 
     $d="pages/"; 
 
     if(isset($_GET['p'])){ 
 
      $p=strtolower($_GET['p']); 
 
     if(preg_match("/^[a-z0-9\-]+$/",$p) && file_exists($d.$p.".html")){ 
 
      include $d.$p.".html"; 
 
     } 
 
     else{ 
 
      include $d."404.html"; 
 
      } 
 
      } 
 
     ?> 
 
\t </div>

而且我onpopstate使用(當我的狀態爲空負荷home.html做爲,否則載入歷史頁面)來模擬歷史。 問題是當我的頁面statut狀態=空(第一頁加載)我的頁面加載兩次,因爲包括,我該如何解決它? 這是我的ajax:

var afficher = function (data, page) { 
 
    $('#container').delay (300).fadeOut (400, function() { 
 
     $('#container').empty(); 
 
     $('#container').append (data); 
 
\t \t $('#container').fadeIn (500, function(){ 
 
     }); 
 

 
    }); 
 
}; 
 

 
var loadPage = function (page, storeHistory) { 
 
    if (typeof storeHistory === 'undefined') { 
 
     var storeHistory = true; 
 
    } 
 
    
 
    $.ajax ({ 
 
     url: 'pages/' + page, 
 
     cache: false, 
 
     success: function (html) { 
 
      afficher (html, page); 
 
      if (storeHistory === true) { 
 
       history.pushState ({ 'key': 'value', 'url': page }, '', page); 
 
      } 
 
     }, 
 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
 
      afficher ('erreur lors du chagement de la page'); 
 
     } 
 
    }); 
 
    
 
    return false; 
 
}; 
 

 
window.onpopstate = function (e) { 
 
    if (e.state === null) { 
 
     loadPage ('home.html'); 
 
    } else { 
 
     loadPage (e [ 'state' ] [ 'url' ], false); 
 
    } 
 
}; 
 

 
$(document).ready (function() { 
 
    $('#menu a').on ('click',function (e) { 
 
     var page = $(this).attr ('href'); 
 
     loadPage (page); 
 
     return false; 
 
    }); 
 
    
 
    $('#container').on ('click', '.vs-transform a', function() { 
 
     var page = $(this).attr ('href'); 
 
     loadPage (page); 
 
     return false; 
 
    }); 
 
});

+0

嘗試:e.preventDefault();在加載任何頁面之前。 –

回答

1

頁面加載某些瀏覽器作爲popstate事件可見。你需要推遲綁定popstate事件,直到頁面加載後:

window.addEventListener('load', function() { 
    setTimeout(function() { 
     window.addEventListener('popstate', function() { 
      //do stuff 
     }); 
    }, 0); 
}); 

here

+0

沒問題,所以實際上它是一個''safari''問題,它在其他瀏覽器中運行良好,謝謝你的回答 – Tiaw

+0

我也在Chrome中看到過它。 – sideroxylon

+0

是的34鉻以前的版本。 – Tiaw