【问题标题】:Javascript: updating DOM element that has been loaded by XMLHttpRequestJavascript:更新已由 XMLHttpRequest 加载的 DOM 元素
【发布时间】:2017-11-12 13:14:32
【问题描述】:

我有一个最终由 XMLHttpRequest 加载的 DIV。在这个新加载的 div 中应该更新(如果存在)

   if (document.getElementById('newdiv') !== null) {
      document.getElementById('newdiv').innerHTML= xhr.responseText;
    }

似乎不起作用。当我对由早期 XMLHttpRequest if (document.getElementById('newdiv') !== null) 插入的元素运行此检查时,返回 null 并且不会插入响应。如果我在页面加载时对 DOM 中的元素执行此操作,则它可以工作。

如何更新页面加载后(可能)加载的元素的值?

请不要使用 jquery,仅使用 javascript 编辑澄清

<body>
    <button onclick="f1()">
    <input onchange="f2(this.value)"/>
    <div id="parent"></div>
</body>    
<script>
function f1()  {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {             
      if (xhr.status == 200 && xhr.status < 300) 
        console.log(xhr.responseText);
        console.log(document.getElementById('parent'));
        if (document.getElementById('parent') !== null) {
          document.getElementById('parent').innerHTML= xhr.responseText;
        }
    }  

  postvars = somestuff;
  xhr.open("POST", "req.py", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.overrideMimeType("application/text");
  xhr.send(postvars);
  }



function f2(val)  {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {                
      if (xhr.status == 200 && xhr.status < 300)  
        console.log(xhr.responseText);
        console.log(document.getElementById('newdiv'));
        if (document.getElementById('newdiv') !== null) {
          document.getElementById('newdiv').innerHTML= xhr.responseText;
        }
    }    

  }
  postvars = val;
  xhr.open("POST", "req.py", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.overrideMimeType("application/text");
  xhr.send(postvars);
  }}
</script>

f1 的 xhr.responseText 会像

<div id="newdiv"></div>

f2 的 xhr.responseText 会像

fancy text

【问题讨论】:

  • 你如何将#newdiv 插入到 DOM 中? console.log(document.getElementById('newdiv')); 究竟会产生什么?
  • 我正在插入并加载一个 XMLHttpRequest innerHTML= xhr.responseText;到 newdiv 的父级
  • 你能edit你在问题中使用的代码吗?我仍然不明白这是如何创建您要插入响应的#newdiv

标签: javascript html ajax xmlhttprequest


【解决方案1】:

删除 !=null 条件,因此每个请求都会显示新数据

【讨论】:

  • 为什么删除!== null 有帮助?当元素不存在时,document.getElementById 何时返回 null 以外的任何内容?
  • 我没有得到,你到底在看什么?你想在加载页面时使用 javascript 执行该功能吗?
  • 我只是想让你解释一下,为什么你认为 document.getElementById('newdiv')document.getElementById('newdiv') !== null 作为条件并不等同,因为你说删除 !== null 会有所帮助,这意味着它们'd'd不等价。代码使用xhr.responseText,所以这不能在页面加载中,而是在 XHR 回调中。
猜你喜欢
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 2023-03-02
相关资源
最近更新 更多