php – 会话变量从while循环发送特定变量

前端之家收集整理的这篇文章主要介绍了php – 会话变量从while循环发送特定变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个简单的while循环,它从 mysql查询中检索数据并在我的主页上显示几个链接.

我想避免使用PHP get函数并将查询字符串添加到我的URL

我正在考虑使用会话变量,但我需要帮助,我很确定无法做到这一点.

当访问者点击while循环显示的几个链接时,该特定变量将在会话中设置.

在我的代码中,会话将始终发送最后一个var.

可以这样做吗?

<? session_start(); // Start Session Variables

    $result = MysqL_query("my query");

    while($slice = MysqL_fetch_assoc($result)){
        $url = $slice['url'];
        $name  = $slice['name']; ?>

        <a href="<? echo $url; ?>"><? echo $name; ?></a>

    <? } 

    $_SESSION['name'] = $name; // Store session data  ?>
您可以通过使用javascript函数来完成您的操作,该函数将使AJAX请求将所单击的名称发送到服务器.然后,服务器端代码将存储所需的会话变量
<? 
     session_start(); // Start Session Variables

    $result = MysqL_query("my query");
    $name = '';
    while($slice = MysqL_fetch_assoc($result)){
        $url = $slice['url'];
        $name  = $slice['name']; ?>

        <a href="<? echo $url; ?>" onclick='setSession(<? echo $url;?>);'><? echo $name; ?></a>

    <? }

现在,setSession将通过AJAX调用传递获得的值.然后可以通过简单的服务器端代码将其保存为会话URL

与包含链接页面在同一页面显示的JavaScript代码

<script type='text/javascript'>
    function getXMLHTTPRequest() {
    try {
    req = new XMLHttpRequest();
    } catch(err1) {
      try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (err2) {
        try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (err3) {
          req = false;
        }
      }
    }
    return req;
    }



      var http = getXMLHTTPRequest();
       function setSession(value) {
    var myurl = "session.PHP";  // to be present in the same folder
     var myurl1 = myurl;
      myRand = parseInt(Math.random()*999999999999999);
      var modurl = myurl1+"?rand="+myRand+"url"+value ; // this will set the url to be sent

      http.open("GET",modurl,true);
      http.onreadystatechange = useHttpResponse;
      http.send(null);
    }


    function useHttpResponse() {
       if (http.readyState == 4) {
        if(http.status == 200) {
          var mytext = http.responseText;
          // I dont think u will like to do any thing with the response
          // u can redirect the user to the req page (link clicked),once the session url has been setted
            }
         }
         else {
             // don't do anything until any result is obtained
            }
        } 
</script>

要存在的PHP服务器端代码,以将所需的url设置为会话值

<?PHP
session_start();
if($_SESSION['url']!=""){
unset($_SESSION['url']);   
$_SESSION['url'] = $_REQUEST['url'];  
}
else {
$_SESSION['url'] = $_REQUEST['url'];  
}
?>
原文链接:https://www.f2er.com/php/133941.html

猜你在找的PHP相关文章