如何使用cookie将变量传递到下一页

时间:2016-07-07 16:08:13

标签: javascript php

我正在设计一个房地产网站。我的网站上有很多广告,感谢我的朋友Arsh Singh,我创造了一个最受欢迎的广告。或者'保存'每个帖子上的按钮,用于根据用户在特定页面中保存所选页面标题,以便用户在需要时查看帖子。
现在,当用户点击"添加到收藏夹"时,我想将广告的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>
&#13;
&#13;
&#13;

&#13;
&#13;
//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);
        });
      });
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:4)

Cookie中的JSON 您可以使用JSON通过序列化JSON将详细信息(id,post name等)存储到cookie中: jquery save json data object in cookie

但是,出于安全考虑,您不应将数据库表名存储在Cookie中。

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

答案 1 :(得分: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等的变量。

答案 2 :(得分:1)

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这是重构的代码,效果更好(来自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();
});