将 PHP 变量传递给函数时在 PHP 中调用 Javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32666339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling Javascript function in PHP while passing PHP variables into the function
提问by Ramtin Soltani
I'm experiencing a problem when calling a JavaScript function inside PHP code and trying to pass my PHP variables as parameters into the function. While it seems really simple to me, I can't figure it out by trying different syntax.
我在 PHP 代码中调用 JavaScript 函数并尝试将我的 PHP 变量作为参数传递给函数时遇到问题。虽然对我来说似乎很简单,但我无法通过尝试不同的语法来弄清楚。
Here is a sample code which can demonstrate the problem:
这是可以演示问题的示例代码:
<?PHP
$var1 = 0;
$var2 = 1;
$var3 = 2;
echo '<script type="text/javascript">functionName($var1, $var2, $var3);</script>';
?>
If I try to pass constants (e.g. "123") the function gets called and the value is passed, but when trying to pass the PHP variable, the function doesn't get called at all.
如果我尝试传递常量(例如“123”),则会调用该函数并传递该值,但是在尝试传递 PHP 变量时,该函数根本不会被调用。
How can I do this correctly?
我怎样才能正确地做到这一点?
回答by aldrin27
Single quotes litterally puts your
$var
as$var
. While double quotes puts your$var
in0 1 or 2
单引号字面上把你的
$var
as$var
。虽然双引号把你$var
放在0 1 or 2
echo "<script type='text/javascript'>functionName('$var1', '$var2', '$var3');</script>"
回答by 1000Gbps
I think you should use curly braces to better distinguish variables in a string. Just wrap them like this:
我认为您应该使用花括号来更好地区分字符串中的变量。只需像这样包装它们:
echo "<script type='text/javascript'>functionName({$var1}, {$var2}, {$var3});</script>"