jQuery-如何转义html以防止XSS? [英] jquery - how to escape html to prevent XSS?

查看:576
本文介绍了jQuery-如何转义html以防止XSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是laravel,当用户发送短信时,其中可能包含一些恶意代码.当我使用{{}}时,它将向我显示用户已发送的确切文本.如果他已发送

I'm using laravel, when a user sends a text message, it may contain some malicious code. When I use {{}} it will show me the exact text the user has sent. If he has sent

<script>alert("malicious")</script>

它会显示完全相同并且很好,但是当我使用jquery ajax时,我将获取的数据放在一些html标记内的某些变量中,最后将它们全部附加到主标记上,如下所示:

it will show exactly the same and it's good, but when I use jquery ajax, I put the fetched data to some variables within some html tags and lastly append all of them to a main tag like so:

   data = '';
    //loop starts here // some otger codes deleted for cleanness
    data += "<h2>"+response.name+"</h2>";
    data += "<p>"+response.description+"</p>";
    $('#mydata').html(data);

现在的问题是,如果我使用html(),则将执行用户恶意代码,如果不执行,则结果将不会显示为html.

and now the problem is that if I use html() the user malicious code will be executed and if I don't, the result will not be shown as html.

我想我应该对$.parseHTML做些事情,对吗?

I guess I should do something with $.parseHTML, isn't it?

谢谢

推荐答案

您应该使用jQuery text()对数据进行编码.

You should use jQuery text() to encode the data.

$('#mydata').text(data);

要创建#mydata的内容,您可以使用

To create the content of #mydata you can use

$('#mydata')
  .html("")
  .append($("<h2></h2>").text(response.name))
  .append($("<p></p>").text(response.description))

这篇关于jQuery-如何转义html以防止XSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆