使用ajax将内容加载到div中

时间:2014-06-26 11:42:48

标签: javascript php ajax html-parsing

我正在使用ajax javascript将view_login.php中的内容加载到index.php的div id="display"

var hr=new XMLHttpRequest();
hr.open("GET", 'view_login.php', true);
hr.onreadystatechange = function(){
    if(hr.readyState == 4 && hr.status == 200){
        var return_data = hr.responseText;
        document.getElementById('display').innerHTML = return_data;
    }
}
hr.send();

而不是echo $output我只会瞄准div本身。

PHP / HTML

$output = '
<div id="visible">
<form>
<input type="text" name="name"/>
<input type="submit" />
</form>
</div>';

echo $output;

是否可以只定位div visible及其内容而不是页面上的每个输出?不使用jquery和普通/原始javascript。

1 个答案:

答案 0 :(得分:0)

在纯JavaScript中有几种方法可以做到这一点。一种方法是将HTML附加到Document Fragment,这是一个单独的文档,然后在其上使用querySelector来提取您想要的div。

<强> Demo

var frag = document.createDocumentFragment();
var div = document.createElement('div'); // create a div to contain the HTML
div.innerHTML = return_data; // insert HTML to the div
frag.appendChild(div); // append the div to the document fragment

var visibleDiv = frag.querySelector("#visible"); // find the #visible div

// append the div to the main document
document.getElementById('display').appendChild(visibleDiv);

其他选项包括:

  • DOMParser(由IE9 +支持)。
  • 将其作为div添加到主文档中,但是您需要确保它在视图中隐藏,然后获取div并将其删除。