如何从ajax调用中检索元素

时间:2013-10-23 06:40:50

标签: javascript php ajax

我想从ajax调用中检索所有元素,然后将它们插入到另一个元素中,而不是:

  • 使用jquery(我只想使用纯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。

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

你看过这个

吗?

http://w3schools.com/ajax/ajax_examples.asp

http://w3schools.com/ajax/tryit.asp?filename=tryajax_first

我认为您发现的大多数示例都使用jquery,因为jquery使它跨浏览器

答案 2 :(得分: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;
            }
        }
    }
相关问题