簡體   English   中英

如何獲取ID以在php中設置會話變量

[英]How to get the id to set a session variable in php

第一部分現在沒有任何問題。

    <?php
  session_start();
  while($row = $result->fetch_assoc()){
    echo "<div id='name' style='margin-top:50px;'><h2>" . $row['name'] . "</h2>";
    echo "<a href='nextPage.php'><img class='pic' src='".$row['imageURL']."' data-id='".$row['id']."' height='100px'/></a></div>";
    echo "<div id='bio' style='border-bottom:1px solid #000;'><p>" . $row['bio'] . "</p></div>";
  }
?>

<script type="text/javascript">
  $(document).on('click', '.pic', function(){
    var id = $(this).data('id');
    $.ajax({
      type: 'POST',
      url: 'setSession.php',
      data: {myId: id}
    });
  });
</script>

單擊圖像后,我僅收到php錯誤消息,告訴我有一個未定義的變量。 我目前有“ setSession.php”作為單獨的頁面,不確定是否應該。

**Next Page**

    <?php
    session_start();
    include("connect.php");

    $result = mysqli_query($con, "select * from table");

    mysqli_close($con);
?>
<!doctype html>
<html>
    <head>
        <title></title>
    </head>

    <body>
      <div class="wrapper">
        <img src="<?php echo $row['imageURL'];?>" height="200px"/><br/>
        <div class="textSection" style="text-align:center;">
          <h2><?php echo $row['name'];?></h2>
          <p>
            <?php echo $row['bio'];?>
          </p>
        </div>
      </div>

    </body>
</html>

首先,您應該像這樣在該頁面中開始會話。

session_start();

然后像這樣訪問會話變量。

$_SESSION['your_key_here'];// this will return the value stored in session.

將數據屬性data-id放在img標簽上,並將ids更改為class因為ids應該是唯一的,如下所示:

<img class='pic' src='" . $row['imageURL'] . "' data-id='" . $row['id'] . "' height='100px'/></a></div>";

並使用其classAJAX請求將click handler注冊到img ,以將data id設置為session變量,如下所示:

$(document).on('click', '.pic', function() {

   var id = $(this).data('id'); // get id value from data-id attribute
   $.ajax({
     type : 'POST',
     url : 'setSession.php',
     data : {
      myId : id
     },
     success : function(msg) { /* do something here for success request */ }
  });
});

最后。 setSession.php頁面中:

<?php
  session_start();
  $_SESSION['id'] = $_POST['myId']; // this come from ajax request
  echo "something"; // and this will available on ajax success callback
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM