2013-10-23 20 views
1

我想要從一個Ajax調用所有元素,然後將其插入另一個元素沒有檢索元素:使用jQuery如何從一個Ajax調用

  • (我只想用純JavaScript)
  • 創建一個新的元素來包含Ajax響應

這是我曾嘗試:

的index.php

<!DOCTYPE HTML>  
    <head> 
     <script type="text/javascript"> 

      function loadPage() { 
       var ajax = new XMLHttpRequest(); 
       ajax.open('GET', 'test.php', true); 
       ajax.onreadystatechange = function(){ 
        if(ajax.readyState === 4 && ajax.status === 200){ 
         document.getElementById('output').appendChild(ajax.responseText) ; 
        } 
       }; 
       ajax.send(); 
       } 

       loadPage(); 
     </script> 
    </head> 
    <body> 
     <div id="output"> 
      <h1>Default</h1> 
     </div> 
    </body> 
    </html> 

test.php的

<h1> 
    its work 
</h1> 

<div> 
    <h2> 
     its work2 
    </h2> 
</div> 

我已經GOOGLE了它,但得到的答覆總是使用jQuery。

+0

您在javascript中創建的每個元素都會返回對該節點的引用。但在ajax調用中沒有參考。所以你不能使用appendChild,而不是使用document.getElementById('output')。innerHTML = ajax.responseText; – Shadow

+0

我不想抹殺元素 – ilike

回答

1

Node.appendChild要求Node對象作爲參數。你從test.php得到的是一個字符串。嘗試使用innerHTML代替

document.getElementById('output').innerHTML = ajax.responseText; 

隨着XHR 2級的,你可以簡單地附加一個onload處理程序XHR而不是檢查readyStatestatus性能。

ajax.onload = function() { 
    document.getElementById('output').innerHTML += this.responseText; 
} 
+0

我不想刪除該分區 – ilike

+0

內標籤

默認

您可以連接現有的'innerHTML'使用'+ ='新的內容標記內

默認

。我已更新我的帖子。 –

+0

感謝您拯救我的生命 – ilike

0

試試這個例子一個

function loadPage(){ 
var strURL="test.php"; 

var req = getXMLHTTP(); 

if (req) { 

req.onreadystatechange = function() { 
if (req.readyState == 4) { 
// only if "OK" 
if (req.status == 200) { 
document.getElementById('output').value=req.responseText; 
    } else { 
alert("There was a problem while using XMLHTTP:\n" + req.statusText); 
} 
} 
} 
req.open("POST", strURL, true); 
req.send(null); 
} 

} 



function getXMLHTTP() { //function to return the xml http object 
    var xmlhttp = false; 
    try { 
     xmlhttp = new XMLHttpRequest(); 
    } catch (e) { 
     try { 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } catch (e) { 
      try { 
       xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
      } catch (e1) { 
       xmlhttp = false; 
      } 
     } 
    }