[英]ajax jquery passing string as a parameter in onclick event jquery
echo "<button onClick='follow(".$name.");'></button>";
I need to pass a string as a parameter in follow(user) function onClick event jquery. But it's getting called as a value.我需要在 follow(user) function onClick 事件 jquery 中传递一个字符串作为参数。但它被作为一个值调用。
I tried kind of everything, but in php it looks a bit of a big deal for me.我尝试了一切,但在 php 中,它对我来说看起来有点大。 Is there any other way around to get the expected result as a string from a php variable.
是否有任何其他方法可以从 php 变量中获取字符串形式的预期结果。
Quotes are off and if you're passing a string you need quotes wrapping the string in the function call.引号已关闭,如果您传递的是字符串,则需要在 function 调用中用引号将字符串括起来。
There is various ways to do it, for standard "
in html properties:有多种方法可以做到这一点,对于 html 属性中的标准
"
:
echo '<button onClick="follow(\''.$name.'\')"></button>';
echo "<button onClick=\"follow('".$name."')\"></button>";
echo "<button onClick=\"follow('$name')\"></button>";
for single quotes对于单引号
echo '<button onClick=\'follow("'.$name.'")\'></button>';
echo "<button onClick='follow(\"".$name."\")'></button>";
echo "<button onClick='follow(\"$name\")'></button>";
But that's presuming your users are nice, a crafty user may create a username with \n
in it, then from POSTing to storing and retrieving it would most likely be rendered as a new line:但这是假设你的用户很好,一个狡猾的用户可能会创建一个包含
\n
的用户名,然后从 POST 到存储和检索它很可能会呈现为一个新行:
<?php
$name = "Foo\nBar";
echo '<button onClick="follow(\''.$name.'\')"></button>';
Rendering the following which would cause the page to break:呈现以下内容会导致页面中断:
<button onClick="follow('Foo
Bar')"></button>
Or worse a username like:或者更糟糕的用户名,例如:
$name = "Foo')\"></button>\n<button onClick=\"window.location.href = ('http://example.com";
Which would render a stored XSS:这将呈现存储的 XSS:
<button onClick="follow('Foo')"></button>
<button onClick="window.location.href = ('http://example.com')"></button>
So a better solution then to directly pass it in, would be to escape it, using htmlentities
and json_encode
so \n
is not rendered by the html.因此,比直接传入它更好的解决方案是使用
htmlentities
和json_encode
转义它,因此 html 不会呈现\n
。
echo '<button onClick=\'follow('.json_encode(htmlentities($name, ENT_QUOTES, 'UTF-8')).')\'></button>';
Which would render to:这将呈现为:
<button onClick='follow("Foo')"><\/button>\n<button onClick="window.location.href = ('http:\/\/example.com")'></button>
Though you should be validating usernames on create before allowing such an attack.尽管在允许此类攻击之前,您应该在创建时验证用户名。
You echo a php variable in javascript without adding quotes thus ending with a javascript variable name instead of a string.您在 javascript 中回显 php 变量而不添加引号,因此以 javascript 变量名称而不是字符串结尾。
Just add escaped quotes like this:只需像这样添加转义引号:
echo "<button onClick='follow(\"".$name."\");'></button>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.