如何将 PHP 字符串传递到 Javascript 函数调用中? [英] How do I pass a PHP string into a Javascript function call?
问题描述
可能的重复:
将 PHP 字符串传递给 Javascript 变量(和转义换行符)
所以,本质上我试图从 PHP 页面传递一个字符串作为 javascript 函数的参数.PHP 包含在脚本所在的页面中,但它们位于两个单独的文件中.
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.
但是,每当我尝试传递字符串时,它都会阻止 javascript 运行.我可以传递 PHP 整数,但不能传递字符串.有没有可能解决这个问题?我一直在互联网上寻找可能导致我的错误的原因,但我找不到任何东西.任何帮助将不胜感激.
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.
$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>
这是javascript函数.
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);}
推荐答案
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>
您需要引用字段.如果您的字段是整数,则不需要引用,如果是字符串,则需要引用.我引用了两者,因为我不知道 parentID 是字符串 id 还是数字 id.当然,做您的应用程序需要的东西.
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.
更新:关于迈克尔关于如果评论包含引用则中断的评论.我们现在转义 $comment 中的所有双引号以防止这种情况发生.
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.
这篇关于如何将 PHP 字符串传递到 Javascript 函数调用中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!