douhao7889
2016-10-07 03:05
浏览 232
已采纳

传递href onclick变量以在PHP中运行

I am trying to pass variables stored in href links to a function. Im able to define the variables from the query results. My problem is passing it to the function once the hyperlink is clicked. This is my code:

<?php
    foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
    {
      echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
    } 
?>

This is the function:

<script> 
function hrefClick($course){
      $newCourse=$course;
}
</script>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongluolie3487 2016-10-14 14:38
    已采纳

    I was able to find a way to get it done? It seems pretty straightforward. This is what I came up with.

    <?php
        foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
          echo  "<form name='course".$row['courseID']."' action='index.php' method='GET'/>";
          echo "<a href='javascript: document.course".$row['courseID'].".submit();'/>".$row['courseID']."</a>";
          echo "<input type='hidden' name='courseID' value='".$row['courseID']."'/><br>";
          echo "</form>";
        } 
      ?>
    
    已采纳该答案
    打赏 评论
  • drpfu51608120170 2016-10-07 04:04

    PHP Code :

    <?php
        foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
        {
          echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
        } 
    ?>
    

    Function should be as:

    <script> 
    function hrefClick(course){
          // You can't define php variables in java script as $course etc.
          var newCourse=course;
          alert(newCourse);
    }
    </script>
    
    打赏 评论
  • duanji5569 2016-10-07 04:43

    We will be using two file here. From file1.php onclicking the link we will send the data via Ajax to file2.php. It is a Jquery based solution.

    //file1.php
    <?php
    foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
        echo '<a href="javascript:void()" data-href="'.$row['courseID'].'"/>'.$row['courseID'].'</a><br>';
    }
    ?>
    <script>
        $('a').click(function(){
            var hrefData = $(this).attr('data-href');
            if (typeof hrefData !== typeof undefined && hrefData !== false) {
                alert(hrefData);
                //or You can post the data
                $.post( "file2.php", { courseid:hrefData} );
            }
        });
    </script>
    

    You can retrieve the result on file2.php

    //file2.php
    <?php
    if(isset($_POST['courseid'])){
        $newCourse = $_POST['courseid'];
    }
    ?>
    
    打赏 评论

相关推荐 更多相似问题