简体   繁体   English

使用Ajax将内容加载到div中

[英]Load content into div using ajax

I'm Loading in content from view_login.php into index.php´s div id="display" using ajax javascript 我正在使用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();

Rather than echo $output i would just target the div itself. 而不是echo $output我只会针对div本身。

PHP/HTML PHP / HTML

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

echo $output;

is it possible to just target the div visible and it contents instead of every ouput on the page? 是否可以仅将div visible且其内容作为目标,而不是页面上的每个输出? without using jquery and just plain/raw javascript. 而不使用jQuery,而只是简单/原始的JavaScript。

There are a few ways of doing this in plain JavaScript. 有几种使用普通JavaScript进行此操作的方法。 One way would be to append the HTML to a Document Fragment , which is a separate document, then use querySelector on it to pull out just the div you want. 一种方法是将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);

Other options are: 其他选项是:

  • DOMParser (supported by IE9+). DOMParser (受IE9 +支持)。
  • Append it as a div to the main document, but you'll need to make sure it's hidden from view, then get the div and remove it. 将它作为div追加到主文档中,但是您需要确保它在视图中是隐藏的,然后获取div并将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM