I'm trying to dynamically add content stored in a variable. However, single quotes are causing problems.
var dynamicelementcode = $("<div id='container'>" + data + "</div>");
dynamicelementcode.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
If the data variable contains a single quote, it breaks my code. How can I solve this problem? The data variable gets its content from a serverside php script.
Any php/js/jquery solution appreciated
Edit:
PHP Code Serverside
$comment_body = "The boy's bicycle";
echo '{ "author": "'.$author.'", "message": "'.$comment_body.'","parentid": "'.$parent_id.'","currentid": "'.mysql_insert_id().'","timestored": "'.$timestampa.'" }';
Jquery Code, Clientside
var newrootcomment = $("<div class='comment'><div class='comment-holder'><div class='comment-body'>"+ data.message + "</div> <abbr class='timestamp' title=''>" + data.timestored + "</abbr><div class='aut'>" + data.author + "</div> <a href='#comment_form' class='reply' id='id"+ data.currentid + "'&开发者_高级运维gt;Reply</a> </div> </div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
var dynamicelementcode = $('<div id="container">').text(data)
jQuery text function automatically escapes quotes for you.
UPD. Escaping only single quotes:
var dynamicelementcode = $('<div id="container">').html(data.replace(/'/g,'''))
UPD 2. If you look at the source of your page you'll see something like "message": 'The boy's bicycle'
- that's a syntactic error.
Here's a better way to pass PHP data to JavaScript, works with quotes too:
$comment_body = "The boy's bicycle";
echo json_encode(array(
'author' => $author,
'message' => $comment_body,
'parentid' => $parent_id,
'currentid' => mysql_insert_id(),
'timestamp' => $timestamp
));
jQuery already has methods to insert text, you don't need to concatenate strings or take care yourself of escaping. Use the .text()
method:
var dynamicelementcode = $('<div id="container"></div>').text(data);
Reference and examples: http://api.jquery.com/text/#text2
精彩评论