简体   繁体   中英

Prevent XSS in javascript on data received by ajax

I receive data from a database and adds the result to an HTML element using jQuery ajax like this:

$.ajax({
    url: "getDatabaseData.php",
    type: "post",
    dataType: "json",
    success: function(response){
        $("#message-div").html(response[0].user_input_message);
    }
});

Here is the getDatabaseData.php that gets and returns the data from the database:

$messages = $CFG_DB->select("SELECT user_input_message FROM messages");
echo json_encode($messages);

Imagine for example if user_input_message contain the following text:

<script>XSS Attack code goes here</script>

My questions are:

  1. Will there be an XSS issue when doing like this?
  2. In case there is an issue, how can I prevent it?

Without ajax, when printing the data using PHP I just use htmlentities to prevent XSS, but I have not seen any similar for javascript.

when printing the data using PHP I just use htmlentities to prevent XSS

The equivalent is to use text() instead of html() .

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