2016-07-29 98 views
0

有一個顯示博客帖子標題列表的主要源。點擊標題時,我需要在新的HTML文件中顯示博客文章的詳細信息。下面是我當前的代碼:使用AJAX,如何設置尚未加載到DOM中的元素的innerHTML?

window.location.href = "/viewpost.html"; 


    postID = this.id; 


    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) { 
      document.getElementById("view-post-container").innerHTML = xmlhttp.responseText; 
     } 
    }; 


    xmlhttp.open("GET", "viewpost.php?q=" + postID, true); 
    xmlhttp.send(); 

的問題是,在元素瀏覽後的容器,是在文件viewpost.html,所以我不認爲PHP文件都可以訪問它。我只是在當前頁面(index.php)上顯示數據,但我希望爲每個帖子都有單獨的頁面,這樣我最終可以學習如何獲得用於搜索引擎優化和共享目的的動態URL。最終目標是擁有動態網址,所以也許有更好的方法?任何幫助將不勝感激。謝謝。

回答

0

只是試試這個,你必須把你的代碼在的window.onload功能

window.onload = function() { 
    if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } else { 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      document.getElementById("view-post-container").innerHTML = xmlhttp.responseText; 
     } 
    }; 
    xmlhttp.open("GET", "viewpost.php?q=" + postID, true); 
    xmlhttp.send(); 
} 
相關問題