Javascript onclick事件中的引号

Javascript onclick事件中的引号,javascript,php,jquery,Javascript,Php,Jquery,我有一个onclick事件,如下所示 <div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')"></div> function display_function(user_id,student_id,student_name) { alert(user_i

我有一个onclick事件,如下所示

<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')"></div>


function display_function(user_id,student_id,student_name)
{
   alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
您需要添加一个调用,以围绕要回显的数据进行调用。
不这样做会使您的代码暴露于XSS攻击。

您需要添加一个调用,以调用您希望回显的数据。
不这样做会使您的代码受到XSS攻击。

使用PHP函数addslashes

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

使用PHP函数addslashes

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

您可以使用
escape()


您可以使用
escape()


这是因为您在函数中以单引号传递值。当名称只有一个引号时,这将导致错误

试试双引号,比如

<div onclick="display_function(\"<?php echo $user_id;?>\",\"<?php echo $student_id;?>\",\"<?php echo $student_name;?>\")"></div>
\”,\”\”>

这是因为您在函数中以单引号传递值。当名称只有一个引号时,这将导致错误

试试双引号,比如

<div onclick="display_function(\"<?php echo $user_id;?>\",\"<?php echo $student_id;?>\",\"<?php echo $student_name;?>\")"></div>
\”,\”\”>

只需添加\before'即可告诉脚本它是一个字符串。我希望有帮助

<?php 
    $user_id = 1;
    $student_id = 1;
    $student_name = "Cheng\'li";
?>

<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')">Click</div>

<script>
function display_function(user_id,student_id,student_name)
{
   alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
</script>

只需添加\ before'来告诉脚本它是一个字符串。我希望有帮助

<?php 
    $user_id = 1;
    $student_id = 1;
    $student_name = "Cheng\'li";
?>

<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')">Click</div>

<script>
function display_function(user_id,student_id,student_name)
{
   alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
</script>

htmlentities()
更适合这种情况,就像Entorax的回答一样。@Barmar我认为student_name不会包含html相关的内容,它只是带有引号的字符串。html标记呢?如果它是由用户提供的,您无法确定它可能包含什么@Rajeshkawat除非他的代码的另一个区域清理了这些数据,否则它可能包含html,因此应该使用htmlentities来保护它(仅仅因为某些事情不应该发生,并不意味着它不会发生)
htmlentities()
更适合这种情况,正如Entorax的回答一样。@Barmar我认为student_name不会包含html相关的内容,它只是带有引号的字符串。html标记呢?如果它是由用户提供的,您无法确定它可能包含哪些内容@rajeshkakawat除非他的代码中的另一个区域清理了这些数据,否则它可能包含html,因此应该使用htmlentities来保护它(仅仅因为某些事情不应该发生,并不意味着它不会发生),他从数据库中获取值,而不是文字。谢谢Barmar。我已经编辑了我的答案。我想他最好是从数据库中获取价值,而不是文字。谢谢你,巴尔马。我已经编辑了我的答案。我想会更好