简体   繁体   中英

Moving from using innerHTML for an AJAX response. (Code is not getting a response)

I am currently using the code as seen below but it is insecure and can be used to exploit the website using XSS.

Old Code, that works:

document.getElementById('response').innerHTML = xmlHTTP.responseText;

New code that is giving no response:

var divContent = xmlHTTP.responseText;            
  var getRes = document.getElementById('response');
  if (getRes.innerText) {
      getRes.innerText = divContent; //For Safari, Google Chrome and MSIE.
  }
  else
  if (getRes.textContent) {
      getRes.textContent = divContent; //For Firefox.
    }   
}

The basic HTML Div below:

<div id="response"></div>

Furthermore the output is HTML, not text.

The div is empty. If innerText or textContent are defined, then they will be empty strings. Empty strings are not true values.

Create text nodes instead, they are standard and well supported.

document.getElementById('response').appendChild(
    document.createTextNode(
        xmlHTTP.responseText
    )
);

If you need to empty the element first you can always:

document.getElementById('response').innerHTML = "";

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