[英]Javascript function with vars on PHP print: quotes
I was just wondering if there is a better way to write down this PHP vars passed to a javascript function called inside a PHP print.: 我只是想知道是否有更好的方法来记下传递给PHP打印内部的javascript函数的PHP变量:
while($nav = mysqli_fetch_array($nav_db)){
print '<li>
<a href="#" onclick="getProductPage('.$nav['id'].', \''.$name.'\')">
'.$nav['Data'].'
</a>
</li>';
}
where 哪里
$nav['id']
is an INTEGER so I don't need extra '' for the JS, and 是一个INTEGER所以我不需要额外的''为JS,和
$name
is not an INTEGER so I need those \\' \\' for the JS. 不是INTEGER所以我需要JS的那些\\'\\'。
Especially this step: 特别是这一步:
getProductPage('.$nav['id'].', \''.$name.'\')
Thank you 谢谢
<?php while($nav = mysqli_fetch_array($nav_db)): ?>
<li>
<a onclick="getProductPage(<?php echo $nav['id']; ?>, '<?php echo $name; ?>')">
<?php echo $nav['Data']; ?>
</a>
</li>
<?php endwhile; ?>
You should break out of PHP to write html. 你应该打破PHP编写html。 It is cleaner this way.
这样更干净。 Also, you had a rogue
</span>
in there and no need for a <br>
in a <li>
menu. 此外,你有一个流氓
</span>
,而且<li>
菜单中不需要<br>
。 Also, an a
tag should have an href
value in there, even if it is #
or javascript:void(0)
or something. 此外,
a
标签应该有一个href
值,即使它是#
或javascript:void(0)
或其他东西。
You should use json_encode
to pass variables from php to javascript. 你应该使用
json_encode
将变量从php传递给javascript。 That will make sure that there are no unescaped characters that can break your javascript. 这将确保没有未转义的字符可以破坏您的JavaScript。
So json_encode($name)
instead of $name
, etc. 所以
json_encode($name)
代替$name
等。
For your example: 对于你的例子:
print '<li>
<a onclick="getProductPage(' . (int) $nav['id'].', ' . json_encode($name) . ')">
' . htmlspecialchars($nav['Data']) . '
</a>
</li>';
have you considered using jquery and ajax send data to a php file and send back json_encode array to javascript? 你考虑过使用jquery和ajax将数据发送到php文件并将json_encode数组发送回javascript吗?
example 例
after you send ajax call to php with datatype json, send back vars like this 在使用数据类型json向php发送ajax调用之后,发回这样的变量
$data['id'] = nav['id'];
echo json_encode($data);
or just $nav['id']
echo json_encode($nav)
in your javascript. 在你的JavaScript中。 on success, you can retrieve the id value like this
成功时,您可以像这样检索id值
ajax{(
blah,
blah,
...
success(msg){
alert(msg.id)
}
})
you can access the var as an object the code above will alert the value of the id. 您可以将var作为对象访问,上面的代码将提醒id的值。 you can assign msg.id to a javascript var or pass it to a function ...ect
您可以将msg.id分配给javascript var或将其传递给函数...等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.