2013-10-23 21 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; 
      } 
     } 
    }