我有一个php代码,我从另一个页面中获得ID,我想将此变量(ID)保存在使用JavaScript的cookie中。我是JavaScript的新手,但是经过大量搜索,我可以编写一些代码。这是我当前的代码,请看一下我认为问题是我如何定义

问题描述 投票:0回答:2
无法访问,而这是无法访问的

<html> <body> <a id="addTofav">Add me to fav</a> <?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"); while($row = mysqli_fetch_array($result)): $price=$row['price']; $rent=$row['rent']; $room=$row['room']; $date=$row['date']; echo"price"; echo"room"; echo"date"; endwhile; ?> </body> </html>

    /*
      * 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(){
        var favID;
        var query = window.location.search.substring(1);
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            var favID = (pair[0]=='ID' ? pair[1] :1)
        }
        $(document.body).on('click','#addTofav',function(){
        var fav = {'$ID':favID};
        faves.push(fav);
        var stringified = JSON.stringify(faves);
        createCookie('favespages', stringified);
        location.reload();
        });
      var myfaves = JSON.parse(readCookie('favespages'));
        if(myfaves){
        faves = myfaves;
        } else {
        faves = new Array();
        }
      });

问题是您的JavaScript,我认为这是在另一个文件中,不知道PHP。您可以执行以下操作以在JavaScript变量中定义
$ID
<html>
    <body>
        <a id="addTofav">Add me to fav</a>
        <?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");
            while($row = mysqli_fetch_array($result)):
                $price=$row['price'];
                $rent=$row['rent'];
                $room=$row['room'];
                $date=$row['date']; 
                echo"price";
                echo"room";
                echo"date";
            endwhile;
        ?>


        <!-- This part is what you want -->


        <script>
            var favID = <?php $ID ?>; // this gets the variable from PHP and saves it in the javascript variable.
            document.cookie = 'my_id='+favID+'; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/' // save it to a cookie
        </script>


       <!-- till here -->


    </body>
</html>
javascript cookies
2个回答
1
投票

var nameEQ = "my_id="; var ca = document.cookie.split(';'); var retrieved_id = null for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) retrieved_id = c.substring(nameEQ.length,c.length); } console.log(retrieved_id) // here you will find your ID

现在我还没有测试过。从理论上讲,它应该起作用。
    

查找您的要求后,
你应该移动这个
$ID = $_GET['ID'] : $ID = 1;

在JavaScript方面。如您所说,您想要更好的清洁代码。 您应该使用JavaScript访问从URL传递的参数。

var query = window.location.search.substring(1); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); var ID = (pair[0]=='ID' ? pair[1] :1) }
then ID很容易适用于您的js.
您的JS:

$(function(){ var favID; var query = window.location.search.substring(1); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); var favID = (pair[0]=='ID' ? pair[1] :1) } $(document.body).on('click','#addTofav',function(){ var fav = {'$ID':favID}; faves.push(fav); var stringified = JSON.stringify(faves); createCookie('favespages', stringified); location.reload(); });

1
投票
Edit:

您可以使用
localstorage

。 在当前页面

`localStorage.getItem('ID',10)`
在您想访问它的其他页面上。
    

localStorage.getItem('ID');

感谢我所有的朋友(Riyaj Khan和Anubhav),最后我得到了答案。替换此JavaScript代码而不是问题JavaScript,您会发现它的工作方式就像char.ch。此U代码可以在cookie中保存ID,然后在您想要的任何地方检索它

<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>


    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.