简体   繁体   中英

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

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.

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? without using jquery and just plain/raw javascript.

There are a few ways of doing this in plain 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.

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+).
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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