开发者

Javascript Function Accepting PHP Variables

开发者 https://www.devze.com 2023-03-09 09:51 出处:网络
I\'m drawing a complete blank why this isn\'t working. I can do it with one variable passing through, but not two. When I use actually numbers like getnt(1,2) it works. It\'s just not working with two

I'm drawing a complete blank why this isn't working. I can do it with one variable passing through, but not two. When I use actually numbers like getnt(1,2) it works. It's just not working with two PHP variables.

  <script type="text/javascript">
  function getnt(nid,pnid) {
      window.location = "nt.php?nid=" + nid + "&pnid=" + pnid开发者_JS百科;
  }
  </script>
  <body>  
  <?php
    echo "<a href='#' onclick='getnt($nid,$pnid)'>VIEW</a>";
  ?>
  </body>

I can make the code work with echo "<a href='nt.php?nid=$nid&pnid=$pnid'>VIEW</a>";, but that's no good if I want to add in alerts and javascript commands.


If the ID and pnID are strings, enclose them with brackets like this.

<body>  
  <?php
    echo "<a href='#' onclick=\"getnt('$nid','$pnid')\">VIEW</a>";
  ?>
  </body>

If still not working, You can debug your code

  1. View the source code in browser, make sure it generates correctly.
  2. Put some alert messages in the javascript function. Install Firebug if you have Firefox or see

  3. Javaascript console if you get any javascript errors.


You could always try:

<script type="text/javascript">
    function getnt(nid,pnid) {
        window.location = "nt.php?nid=" + nid + "&pnid=" + pnid;
    }
</script>
<body>  
    <a href="#" onclick="getnt(<?php echo $nid; ?>,<?php echo $pnid; ?>)">VIEW</a>
</body>


Your question is probably best answered by looking at the rendered HTML source.

In any case, here's how I'd do it using graceful degradation

<script type="text/javascript">
function getnt(element) {
    var href = element.href;
    var nid = element.getAttribute("data-nid");
    var pnid = element.getAttribute("data-pnid");
    return true;
}
</script>
<p><a href="nt.php?nid=<?php echo $nid ?>&amp;pnid=<?php echo $pnid ?>"
      data-nid="<?php echo $nid ?>"
      data-pnid="<?php echo $pnid ?>"
      onclick="return getnt(this)">VIEW</a></p>
0

精彩评论

暂无评论...
验证码 换一张
取 消