2013-03-12 104 views
0

當我點擊一個按鈕時,如何在div中加載html?在div中加載html和php頁面

我有功能,但它不工作:

function ajaxFunction(id, url){ 
document.getElementById("sh").style.visibility = 'hidden'; 
    var xmlHttp; 
    try {// Firefox, Opera 8.0+, Safari 
     xmlHttp = new XMLHttpRequest();  
    } catch (e) {// Internet Explorer 
     try { 
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch (e) { 
      try { 
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
      } catch (e) { 
       alert("Your browser does not support AJAX!"); 
       return false; 
      } 
     } 
    } 

    xmlHttp.onreadystatechange = function(){ 
     if (xmlHttp.readyState == 4) { 
      //Get the response from the server and extract the section that comes in the body section of the second html page avoid inserting the header part of the second page in your first page's element 
      var respText = xmlHttp.responseText.split('<body>'); 
      elem.innerHTML = respText[1].split('</body>')[0]; 
     } 
    } 

    var elem = document.getElementById(id); 
    if (!elem) { 
     alert('The element with the passed ID doesn\'t exists in your page'); 
     return; 
    } 

    xmlHttp.open("GET", url, true); 
    xmlHttp.send(null); 
} 

而且我有按鈕,點擊它。

<button type="button" name="new metere" value="" class="button" onclick="ajaxFunction('test','newmetere.html');">new metere</button> 

當我把newmetere.php功能不起作用,並獲得垃圾值。

+0

我討厭成爲'那個人',但你可能想看看jQuery。在任何人生氣之前,這意味着你直接進入現代教程,jQuery鼓勵事件綁定而不是onclick類型的東西。 – 2013-03-12 16:29:26

+0

你提到newmetere.php無法加載,但我假設您的示例工程中的.html擴展名。簡單的點,但你確定你的服務器正在服務.php?你能直接訪問newmetere.php頁面嗎?那裏的產量是多少?你100%肯定沒有錯別字? – TommyBs 2013-03-12 16:35:19

回答

0

嘗試jQuery's load():這是一種使用Ajax在網頁中異步加載另一頁內容的快速簡單方法!