JavaScript and JQuery - Encoding HTML
I have a web page that has a textarea defined on it like so:
<textarea id="myTextArea" rows="6" cols="75"></textarea>
There is a chance that a user may enter single and double quotes in this field. For instance, I have been testing with the following string:
Just testin' using single and double "quotes". I'm hoping the end of this task is comin'.
Additionally, the user may enter HTML code, which I would prefer to prevent. Regardless, I am passing the contents of this textarea onto web service. I must encode the contents of the textarea in JavaScript before I can开发者_如何转开发 send it on. Currently, I'm trying the following:
var contents $('<div/>').text($("#myTextArea").val()).html();
alert(contents);
I was expecting contents to display
Just testin' using single and double "quotes". I'm hoping the end of this task is comin'.
Instead, the original string is printed out. Beyond just double-and-single quotes, there are a variety of entities to consider. Because of this, I was assuming there would be a way to encode HTML before passing it on. Can someone please tell me how to do this?
Thank you,
If you're sending to a web service, you'll presumably be URL-encoding these (as part of a POST, for instance, either via form submission of Ajax). That will handle any necessary escaping at your end. The service at the other end is responsible for interpreting the input string correctly. If the service doesn't accept HTML tags, it's the service's job to do the necessary entity encoding (or whatever other kind of encoding it wants).
If the service doesn't take responsibility for this, it's open to errors in the client and attacks by people with nefarious intent. So it's really the other end's problem.
By using:
var contents = $("<div/>").text($("#myTextArea").val()).text();
alert(contents);
You display the textual contents instead of the contents in html.
精彩评论