问题
Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)
So, essentially I am trying to pass a string from a PHP page as an argument for a javascript function. The PHP is included in the page that the script is on, but they are in two separate files.
However, whenever I try to pass a string, it stops the javascript from running. I can pass PHP integers, but not strings. Is it possible to fix this? I've been looking around the internet for what might be causing my error, but I can't find anything. Any help would be greatly appreciated.
This is the PHP and HTML. The function runs when submit is clicked.
$comment = "7b";
echo"
<table>
<p><input type='text' id='newPostComment' value='' placeholder='WRITE YOUR COMMENT HERE...' size='35'/><input type='submit' value='UPLOAD' onclick='uploadPostComment($parentID, $comment);fetchComment()'/></p>
</table>
This is the javascript function.
function uploadPostComment(PostCID, Comment){
var PostCommentData = "fsPostID="+PostCID;
PostCommentData += "&fsPostComment="+Comment;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "uploadPostComment.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", PostCommentData.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
alert("Message Posted");
}
else
{
alert("Oh no, an error occured2");
}
}
};
xmlHttp.send(PostCommentData);}
回答1:
echo"
<table>
<p><input type='text' id='newPostComment' value='' placeholder='WRITE YOUR COMMENT HERE...' size='35'/><input type='submit' value='UPLOAD' onclick='uploadPostComment(\"$parentID\", \"" . str_replace('"', '\"', $comment) . "\");fetchComment()'/></p>
</table>
You need to quote the fields. If your field is an integer it does not need to be quoted, if it is a string it needs to be. I quoted both because I don't know if parentID is a string id or a numeric id. Do what your application needs of course.
Update: in regards to Michael's comment about breaking if comment contains a quote. We now escape all double quotes in $comment to prevent that.
回答2:
<input type='submit' value='UPLOAD' onclick='uploadPostComment($parentID, $comment);fetchComment()'/>
is your culprit, especially uploadPostComment($parentID, $comment);
- if $comment is a string, you need to put quotes in place: uploadPostComment($parentID, \"$comment\");
回答3:
Wrap the string in escaped double quotes like \"$comment\"
$comment = "7b";
echo"
<table>
<p><input type='text' id='newPostComment' value='' placeholder='WRITE YOUR COMMENT HERE...' size='35'/><input type='submit' value='UPLOAD' onclick='uploadPostComment(\"$parentID\", \"$comment\");fetchComment()'/></p>
</table>
来源:https://stackoverflow.com/questions/13905313/how-do-i-pass-a-php-string-into-a-javascript-function-call