doucaigai7176 2014-06-26 11:42
浏览 79
已采纳

使用ajax将内容加载到div中

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.

  • 写回答

1条回答 默认 最新

  • dougai3418 2014-06-26 12:17
    关注

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化