Load Text data as JSON in textarea, and prevent execute this (javascript)
I have a stupid problem load data from DB into textarea using Jquery-ajax.
The problem is, when i try to load the data (send by a echo json_encode() in PHP from DB in TEXT utf8_general_ci) into a textarea i cant use htmlentities (because in textarea show characters not the text) if i put javascript in the database, and then, load into textarea, this load correct the chars, but.. execute the code and show me the result of javascript.
Example:
<?php
if (!empty($_GET['json'])) {
$array = array(
'text1' => 'hello world!',
'text2' => '<script>alert("bu")</script>',
);
echo json_encode($array); die();
}
?>
<script type="text/javascript" src="jquery-1.6.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "?json=true",
type: "POST",
dataType: "json",
success: function(data){
$('textarea[name=area]').val(data.text2);
}
});
});
</script>
<textarea name开发者_StackOverflow中文版="area" cols="80" rows="6"></textarea>
I try with .val(), .html(), data.text2.tostring() (fail), and nothing work, always execute the code.. I think its a simple fail, but dont find a solution if i need to show the correct code in textarea and no special chars.. Any idea?
The TEXTAREA doesn't have value. It has the data between the tags. Try using:
$('textarea[name=area]').html(data.text2);
This code works for me: http://jsfiddle.net/8WXyk/1/
anyway I don't know if it's a feasible solution for your needs.
Basically the code:
- Receives an escaped content from server
- Unescapes and and inject it into textarea (you should use .html() as pointed out by Asken)
This code uses the unescape function from the "unescape" plugin, which can be found here: http://plugins.jquery.com/files/jquery.unescape.js_0.txt
Try:
$('textarea[name=area]').val(data.text2);
instead of HTML. This will blank out the text area and allow you to insert the new value.
精彩评论