jquery Ajax to escape special characters to prevent JS injection using the example _jquery

Source: Internet
Author: User

When using Ajax for a message, a problem has arisen. Because after the message content is written, the content is submitted through Ajax, and the content of the message is added to the page with JS. When browsing the message, it is also done through AJAX requests and then displayed. So, if someone writes a JS statement in a message, The statement is executed. The solution is to escape and display these special characters. If you use the JSTL tag in your JSP, it's easy. Use the <c:out value= "${r.content}"/> This way, it will automatically escape, The parameter Escapexml= "true" is omitted, which is the default. Therefore, do not use El expressions when displaying the content submitted by these users, as El is not automatically escaped, and is better done with c:out. And if it's the AJAX request and then the display, Then use the following method. It's actually very simple.

Copy Code code as follows:

var html= "<script>alert (' asdfasdf ') <\/script>";
$ ("#content"). Text (HTML);

So what happens? The solution is simply to escape these special characters, that is < turn <> to > Use jquery to escape the characters.
Copy Code code as follows:

<script>
var html= "<script>alert (' asdfasdf ') <\/scipt>";
html=$ ("#x"). Text (HTML). html ();
$ ("#content"). Append ("<div>" +html+ "</div>");
</script>
<body>
<spanid= "x" style= "Display:none" ></span>
<divid= "Content" ></div>
</body>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.