简体   繁体   中英

Javascript: updating DOM element that has been loaded by XMLHttpRequest

i have a DIV that is eventually load by a XMLHttpRequest. in this new loaded div should be updates (if exist)

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

seems not working. When i run this check on a Element, which is inserted by an earlier XMLHttpRequest if (document.getElementById('newdiv') !== null) returns null and the response will not be inserted. if i am doing this on an element that is in the DOM on load of the page, it works.

How can i update a value of an Element that has (maybe) loaded after page load?

Please no jquery, javascript only Edit to clarify

<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>

the xhr.responseText for f1 will be like

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

the xhr.responseText for f2 will be like

fancy text

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

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