想在javascript函数中传递php变量作为参数吗?


i want to pass my php variable in one javascript function.
i know it seems simple but i don't know where am i missing something?

    <?php
        while($gg=mysql_fetch_array($lg))
        {
    ?>
        <td id="add_td">
        <?php
        $id = $gg['p_id'];
        echo "<a onclick=cnf('Are you sure you want to delete that?',$id)>"; ?>Delete</a>
        </td>
<?php
        }
?>

and in my javascript function

function cnf(msg,id)
{

     cnf = confirm(msg);
     if(cnf) { 
            parent.location.href = 'p_update.php?d=' + id;          
     }
}

so i need to know on which id that user had clicked so that i will only delete that id from database.
if i try this thing then it showing error on "cnf" function and its saying like "unterminated string literal"?

if $id is not numeric you should write 

<?php
        while($gg=mysql_fetch_array($lg))
        {
    ?>
        <td id="add_td">
        <?php
        $id = $gg['p_id'];
        echo "<a onclick=cnf('Are you sure you want to delete that?','".$id."')>"; ?>Delete</a>
        </td>
<?php
        }
?>

If $id is a string literal, you should put it into quotes when you are passing it as a parameter to cnf() function in <a ... > tag:

echo "<a onclick=cnf('Are you sure you want to delete that?', '$id')>";

Check your syntax

<?php
    while($gg=mysql_fetch_array($lg))
    {
?>
        <td id="add_td">
        <?php
        $id = $gg['p_id'];
        ?>
        <a onclick="cnf('Are you sure you want to delete that?',<?=$id?>);">Delete</a>
        </td>
<?php
     }
?>

I would do something like this instead. HREF is mandatory if you want the "hand" pointer A unique ID is also mandatory on tags and you need to quote the ID if you pass it in the function instead of what I suggest and give the link the id

function cnf(link,id) {
  if (confirm("Are you sure you want to delete "+id) {
    link.href = "p_update.php?d=" + id;          
    return true;
  }
  return false;
}

<?php
  while($gg=mysql_fetch_array($lg)) { 
    $id = $gg['p_id'];
?>
  <td id="add_td<?php echo $id; ?>"><a target="_parent" href="#" id="<?php echo $id; ?>" onclick="return cnf(this)">Delete</a></td>
<?php } ?>
foreach($mas as $k=>$v) {
  //echo $k.' = '.$v.'<br>';
  echo("

    <input type=\"button\" id=\"delete_id".$k."\" value=\"Blablabla\" onclick=\"alert('".$v."');\"/>

  ");
}

If I put there $k (index) it works but if string (value is string), I get an error

unterminated string literal

In HTML tags this works but not as the function argument!

Use quotes around php variable '$id'.

echo "<a onclick=cnf('Are you sure you want to delete that?','$id')>";

Another example, $p is some php variable,

echo "<input type=button value='update' onclick=myfunc('$p')>"