2011-12-20 193 views
3

嗯,我有這樣的事情,加載HTML使用加載根文件的路徑的相對路徑,而不是源文件的路徑

<html> 
<head> 
    <script src="jquery.js" type="text/javascript"></script> 
</head> 
<body> 
    Loading your content... 
</body> 
<script type="text/javascript"> 
    var xmlhttp; 
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } else {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.onreadystatechange=function(){ 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
      $("body").html(xmlhttp.responseText); 
     } 
    }; 

    xmlhttp.open("GET","../stats.phtml",true); 
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
    xmlhttp.send(); 
</script> 
</html> 

而且它並沒有找到加載的文件統計鏈接的任何外部文檔。 phtml(javascript和css源代碼),因爲相對路徑的路徑是文檔的路徑,而不是加載文檔的根路徑。

我需要在AJAX上執行此操作(加載頁面應在執行腳本時加載內容並在3秒後顯示它),所以只需執行window.location ='../stats .phtml'3秒後不是一個好的解決方案。我還想保留已加載文檔中的相關鏈接,而不是將其移至絕對路徑。有什麼建議麼?

回答

2

我發現讀this article on mozilla developer是HTML5 window.history.pushState可以做替代,這樣纔可以使用:

if (xmlhttp.readyState==4 && xmlhttp.status==200) 
{ 
    var stateObj = { foo: "stats" }; 
    window.history.pushState(stateObj, "Title", "../stats.phtml"); 
    $("body").html(xmlhttp.responseText); 
} 

至極對我來說不夠公平。我認爲#標記可以用來識別文檔併爲另一個切換一個URL而不用重新加載(與一些Apache modrewrite法術相結合,將#表示法改爲服務器中的實際目錄,我猜)。如果你確切地知道如何使用這種方法的任何例子,將不勝感激。

更新我一直在這個工作了一段時間,我發現了一個非jquery的替代方案,它取代了整個文檔內容,在這種情況下更適合我。

if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
     var stateObj = { foo: "stats" }; 
     window.history.pushState(stateObj, "Title", "../stats.phtml"); 
     document.open('text/html'); 
     document.write(xmlhttp.responseText); 
     document.close(); // don't forget to do this, or you'll be in trouble! 
    } 

享受!

+0

我目前正在嘗試您的更新中的具體內容,它給我在Firefox中遇到的各種麻煩。看起來像pushstate和document.open並不能很好地協同工作。這是如何在Firefox中爲你工作的? – gmustudent 2013-04-25 17:15:57

+0

這是一年多以前,但我沒有任何麻煩。查看https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method(對不起,對於遲到的答案) – NotGaeL 2013-04-30 17:24:43