i have this jQuery code:
$("#text_a").html('<textarea name = "text">".$text_user."</t开发者_如何学运维extarea>');
And if I put in textarea text with new line i get this error:
unterminated string literal
I get an error with this text:
First line...
Second line ...
Assuming that this is actually a PHP question, I normally use json_encode() to generate JavaScript strings. E.g.:
// Prints: var myString = "Hello\nWorld";
var myString = <?php echo json_encode("Hello\nWorld"); ?>;
Back into JavaScript, you probably want to avoid HTML injection and XSS attacks:
var myTextarea = $('<textarea name="text"></textarea>').text(<?php echo json_encode($text_user); ?>);
$("#text_a").html(myTextarea);
Addendum
A little test case that illustrates the need of proper escaping:
<?php
$text_user = '</textarea><a href="http://www.google.com">Google></a><textarea>';
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
// Proper escaping
var myTextarea = $('<textarea name="text"></textarea>').text(<?php echo json_encode($text_user); ?>);
$("#text_a").html(myTextarea);
// HTML injection
$("#text_b").html('<textarea name="text">' + <?php echo json_encode($text_user); ?> + '</textarea>');
});
//--></script>
</head>
<body>
<div id="text_a"></div>
<div id="text_b"></div>
</body>
</html>
You are mixing PHP with javascript. Could be something like:
var text_user = "<?= nl2br(htmlentities($text_user)) ?>";
$("#text_a").html('<textarea name = "text">'+text_user+'</textarea>');
Concatenation operator in ecmascript is "+", not "." like in PHP.
You can't have line breaks in the middle of a string, you either need:
$("#text_a").html('<textarea name="text">First line...\
Second line ...</textarea>');
Or better in my opinion, escape your newlines, like this:
$("#text_a").html('<textarea name="text">First line...\nSecond line ...</textarea>');
There are a few encoding options, for example:
$("#text_a").html('<textarea name = "text">".json_encode($text_user)."</textarea>');
精彩评论