【问题标题】:how to pass variable to next page with cookies如何使用cookie将变量传递到下一页
【发布时间】:2016-11-10 01:26:28
【问题描述】:

我正在设计一个房地产网站。我的网站上有很多广告,感谢我的朋友 Arsh Singh,我在每个帖子上创建了一个“收藏”或“保存”按钮,该按钮将根据 cookie 将所选页面标题保存在特定页面中,供用户查看帖子当他或她想要的时候。
现在我想在用户点击“添加到收藏夹”时将广告的 id 发送到收藏页面,因此基于 id 我可以从数据库中获取某些广告数据。
我可以这样做吗?如何?这是我当前的代码,它只能将页面标题发送到最喜欢的页面。有什么想法吗?

<!DOCTYPE html>
<html>
<head>
  <title>New page name</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  <script src=favoritecookie.js></script>
</head>
<body>
  <a href="javascript:void(0);" id="addTofav">Add me to fav</a>
  <ul id="appendfavs">

  </ul>
 
 <?php
 error_reporting(0);
include("config.php");
(is_numeric($_GET['ID'])) ? $ID = $_GET['ID'] : $ID = 1;
$result = mysqli_query($connect,"SELECT*FROM ".$db_table." WHERE idhome = $ID");
?>
<?php while($row = mysqli_fetch_array($result)):
$price=$row['price'];
$rent=$row['rent'];
$room=$row['room'];
$date=$row['date'];
?>
<?php 
echo"price";
echo"room";
echo"date";
?>
 <?php endwhile;?> 

</body>
</html>

//favoritecookie.js
/*
      * Create cookie with name and value.
      * In your case the value will be a json array.
      */
      function createCookie(name, value, days) {
        var expires = '',
        date = new Date();
        if (days) {
          date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
          expires = '; expires=' + date.toGMTString();
        }
        document.cookie = name + '=' + value + expires + '; path=/';
      }
      /*
      * Read cookie by name.
      * In your case the return value will be a json array with list of pages saved.
      */
      function readCookie(name) {
        var nameEQ = name + '=',
        allCookies = document.cookie.split(';'),
        i,
        cookie;
        for (i = 0; i < allCookies.length; i += 1) {
          cookie = allCookies[i];
          while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1, cookie.length);
          }
          if (cookie.indexOf(nameEQ) === 0) {
            return cookie.substring(nameEQ.length, cookie.length);
          }
        }
        return null;
      }
      /*
      * Erase cookie with name.
      * You can also erase/delete the cookie with name.
      */
      function eraseCookie(name) {
        createCookie(name, '', -1);
      }

      var faves = new Array();

      function isAlready(){
        var is = false;
        $.each(faves,function(index,value){
          if(this.url == window.location.href){
            console.log(index);
              faves.splice(index,1);
              is = true;
          }
        });
        return is;
      }

      $(function(){
        var url = window.location.href; // current page url
        $(document.body).on('click','#addTofav',function(e){
          e.preventDefault();
          var pageTitle = $(document).find("title").text();
          if(isAlready()){
          } else {
              var fav = {'title':pageTitle,'url':url};
              faves.push(fav);
          }
          var stringified = JSON.stringify(faves);
          createCookie('favespages', stringified);
          location.reload();
        });
        $(document.body).on('click','.remove',function(){
          var id = $(this).data('id');
          faves.splice(id,1);
          var stringified = JSON.stringify(faves);
          createCookie('favespages', stringified);
          location.reload();
        });

         var myfaves = JSON.parse(readCookie('favespages'));
         if(myfaves){
           faves = myfaves;
         } else {
           faves = new Array();
         }
        $.each(myfaves,function(index,value){
          var element = '<li class="'+index+'"><h4>'+value.title+'</h4> <a href="'+value.url+'">Open page</a>  '+
          '<a href="javascript:void(0);" class="remove" data-id="'+index+'">Remove me</a>';
          $('#appendfavs').append(element);
        });
      });

【问题讨论】:

  • 只是对关于 SQL 注入的警告的快速说明,您最好检查is_numeric($_GET['ID']),但您也应该始终至少使用mysqli_real_escape_string() php.net/manual/en/mysqli.real-escape-string.php。并且可以这样写 $ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1; :)

标签: javascript php


【解决方案1】:

这是重构后效果更好的代码(来自SO answer):

/* 
 * Create cookie with name and value. 
 * In your case the value will be a json array. 
 */
function createCookie(name, value, days) {
  var expires = '',
    date = new Date();
  if (days) {
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  }
  document.cookie = name + '=' + value + expires + '; path=/';
}
/* 
 * Read cookie by name. 
 * In your case the return value will be a json array with list of pages saved. 
 */
function readCookie(name) {
  var nameEQ = name + '=',
    allCookies = document.cookie.split(';'),
    i,
    cookie;
  for (i = 0; i < allCookies.length; i += 1) {
    cookie = allCookies[i];
    while (cookie.charAt(0) === ' ') {
      cookie = cookie.substring(1, cookie.length);
    }
    if (cookie.indexOf(nameEQ) === 0) {
      return cookie.substring(nameEQ.length, cookie.length);
    }
  }
  return null;
}
/* 
 * Erase cookie with name. 
 * You can also erase/delete the cookie with name. 
 */
function eraseCookie(name) {
  createCookie(name, '', -1);
}

var faves = {
  add: function (new_obj) {
    var old_array = faves.get();

    old_array.push(new_obj);
    faves.create(old_array);
  },

  remove_index: function (index) {
    var old_array = faves.get();

    old_array.splice(index, 1);
    faves.create(old_array);
  },

  remove_id: function (id) {
    var old_array = faves.get();

    var id_index = faves.get_id_index(id);
    faves.remove_index(id_index);
  },

  create: function (arr) {
    var stringified = JSON.stringify(arr);
    createCookie('favespages', stringified);
  },

  get: function () {
    return JSON.parse(readCookie('favespages')) || [];
  },

  get_id_index: function (id) {
    var old_array = faves.get();

    var id_index = -1;
    $.each(old_array, function (index, val) {
      if (val.id == id) {
        id_index = index;
      }
    });

    return id_index;
  },

  update_list: function () {
    $("#appendfavs").empty();
    $.each(faves.get(), function (index, value) {
      var element = '<li class="' + index + '"><h4>' + value.id + '</h4> <a href="' + value.url + '">Open page</a> ' +
        '<a href="javascript:void(0);" class="remove" data-id="' + value.id + '">Remove me</a>';

      $('#appendfavs').append(element);
    });
  }
}

$(function () {
  var url = window.location.href;

  $(document.body).on('click', '#addTofav', function (e) {
    var pageId = window.location.search.match(/ID=(\d+)/)[1];

    if (faves.get_id_index(pageId) !== -1) {
      faves.remove_id(pageId);
    }
    else {
      faves.add({
        id: pageId,
        url: url
      });
    }

    faves.update_list();
  });

  $(document.body).on('click', '.remove', function () {
    var url = $(this).data('id');

    faves.remove_id(url);
    faves.update_list();
  });

  $(window).on('focus', function () {
    faves.update_list();
  });

  faves.update_list();
});

【讨论】:

    【解决方案2】:

    我终于得到了答案。替换这个javascript代码而不是问题javascript(favoritecookie.js),你会看到它就像一个魅力。有了这个你的代码可以将id保存在cookie中,然后在你想要的任何地方检索它

    <script>
       /*
      * Create cookie with name and value.
      * In your case the value will be a json array.
      */
      function createCookie(name, value, days) {
        var expires = '',
        date = new Date();
        if (days) {
          date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
          expires = '; expires=' + date.toGMTString();
        }
        document.cookie = name + '=' + value + expires + '; path=/';
      }
      /*
      * Read cookie by name.
      * In your case the return value will be a json array with list of pages saved.
      */
      function readCookie(name) {
        var nameEQ = name + '=',
        allCookies = document.cookie.split(';'),
        i,
        cookie;
        for (i = 0; i < allCookies.length; i += 1) {
          cookie = allCookies[i];
          while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1, cookie.length);
          }
          if (cookie.indexOf(nameEQ) === 0) {
            return cookie.substring(nameEQ.length, cookie.length);
          }
        }
        return null;
      }
      function eraseCookie(name) {
        createCookie(name,"",-1);
    }
    
        var faves = new Array();
    	  function isAlready(){
        var is = false;
        $.each(faves,function(index,value){
          if(this.url == window.location.href){
            console.log(index);
              faves.splice(index,1);
              is = true;
          }
        });
        return is;
      }
    $(function(){
    var url = window.location.href; // current page url
        var favID;
        var query = window.location.search.substring(1);
    
    	var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            var favID = (pair[0]=='ID' ? pair[1] :1)
    //alert(favID);
    	}
    	$(document.body).on('click','#addTofav',function(){
    	      if(isAlready()){
          } else {
              var fav = {'favoriteid':favID,'url':url};
              faves.push(fav);//The push() method adds new items (fav) to the end of an array (faves), and returns the new length.
          }
    	var stringified = JSON.stringify(faves);
        createCookie('favespages', stringified);
        location.reload();
    	});
    	    $(document.body).on('click','.remove',function(){
          var id = $(this).data('id');
          faves.splice(id,1);
          var stringified = JSON.stringify(faves);
          createCookie('favespages', stringified);
          location.reload();
        });
      var myfaves = JSON.parse(readCookie('favespages'));
        if(myfaves){
        faves = myfaves;
        } else {
        faves = new Array();
        }
        $.each(myfaves,function(index,value){
          var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4>   '+
          '<a href="javascript:void(0);" class="remove" data-id="'+index+'">Remove me</a>';
          $('#appendfavs').append(element);
        });
    
    });
     </script>

    【讨论】:

      【解决方案3】:

      我会使用纯 PHP... setcookie() 来放置一个 cookie,并在需要时使用 PHP $_COOKIE 将其读回。由于需要存储大量数据,无论是结构化的、相关的还是不相关的,我将创建一个关联数组,相应地填充它,然后在将其保存到 cookie 之前使用 PHP serialize() ;读取时 unserialize():

      保存:

      a) $data = array("ID"=>value, "otherdata"=>value...etc);
      b) $dataPacked = serialize($data);
      c) setcookie("cookieName", $dataPacked);
      

      阅读:

      a) $dataPacked = $_COOKIE["cookieName"];
      b) $data = unserialize($dataPacked);
      

      然后根据需要使用 $data 数组。如果我需要一些带有该数据的 Javascript,我会这样做:

      <script>
      var jsVar = "<?php echo $data['key'];?>";
      

      或者更喜欢循环来从 $data 等中编写更多变量。

      【讨论】:

      • 感谢您的回答。正如您在我添加的问题中看到的那样,基于纯 php 设置 cookie。它运行良好,但我想添加一些其他选项,例如通过按钮单击设置 cookie,或者如果用户单击两次“添加到收藏夹”,我无法在不使用 javascript
      • 如果您想留在页面中并仍然设置 cookie,您可以使用 ajax 到设置 cookie 的 php...使用 POST 将 ID 或任何数据发送到 PHP。但是 cookie 已经设置好了,所以页面需要重新加载才能获得更改
      【解决方案4】:

      Cookie 中的 JSON 您可以通过序列化 JSON 来使用 JSON 将详细信息(id、帖子名称等)存储到 cookie 中: jquery save json data object in cookie

      但是,为了安全起见,您不应将数据库表名存储在 cookie 中。

      PHP cookie 访问 https://davidwalsh.name/php-cookies

      【讨论】:

      • 还要牢记 cookie 在 HTTP 数据流中的处理方式:客户端和主机之间总是存在“往返”。您可以使用任何浏览器的调试功能在 HTTP header 中查看 cookie 传输。 LQQK ,以准确了解正在传递的内容、时间和方式。 (而且,它正在按您的预期传递。“永远不要假设......”)
      • @Mike 啊是的......假设......每个程序员的祸根
      猜你喜欢
      • 1970-01-01
      • 2013-09-14
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2015-12-02
      • 1970-01-01
      相关资源
      最近更新 更多