简体   繁体   English

使用javascript在Cookie中保存变量

[英]save a variable in cookies with javascript

hi i have a php code and i get id from another page in it i want to save this variable (id) in cookies with javascript. 嗨,我有一个php代码,我从另一个页面获取ID,我想用JavaScript将这个变量(id)保存在cookie中。 i am new in java but after a lot of search finally i could wrote some codes. 我是Java的新手,但经过大量搜索,我终于可以编写一些代码了。 this is my current code please take a look at this i think the problem is how i define 这是我当前的代码,请看一下我认为问题是我如何定义
var favID = $ID; in my javascript code please help me thanks 在我的JavaScript代码中,请帮助我,谢谢
ps: please do not suggest saving cookie with pure php because i did it and it works fine but i want to do some fancier stuff with it for example as u see i want to save id in cookies by click wich is not acceiable with php ps:请不要建议用纯PHP保存cookie,因为我做到了,它可以正常工作,但是我想用它做一些更奇特的东西,例如,因为你看到我想通过单击来将id保存在cookie中,所以php不可接受

 <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(); } }); 

The problem is your javascript, which I assume is in a different file, is not aware of PHP. 问题是您的JavaScript(我认为它在其他文件中)不了解PHP。 You can do the following to define the $ID in the javascript variable 您可以执行以下操作以在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>

Now on some other page here is how you can get the cookie value: 现在在其他页面上,您可以了解如何获取Cookie值:

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

Now I haven't tested this. 现在我还没有测试。 Theoretically it should work though. 从理论上讲,它应该可以工作。

After looking your requirement, You should move this $ID = $_GET['ID'] : $ID = 1; 在查看了您的需求之后,您应该移动$ID = $_GET['ID'] : $ID = 1; on Javascript side.As you say,you want better clean code.Don't messup JS and PHP in single file.It's bad one 在Javascript方面。正如您所说,您想要更好的干净代码。不要在单个文件中混用JS和PHP。这很糟糕

You should use javascript to access the parameter passed from URL. 您应该使用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 is easily available to your JS. 然后,您的JS即可轻松获得ID。

YOUR 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();
    });

EDIT : 编辑:

You can use localStorage . 您可以使用localStorage on current page 在当前页面上

`localStorage.getItem('ID',10)`

On other page where you want to access it. 在您要访问它的其他页面上。 localStorage.getItem('ID');

thanks to all of my friends ( RIYAJ KHAN and Anubhav)finally i got the answer. 最后,感谢我所有的朋友(RIYAJ KHAN和Anubhav)。 replace this javascript code instead of question javascript and you will see that it works like a charm.with this u code can save id in cookie and then retrieve it where ever u want 替换此javascript代码而不是问题javascript,您将看到它的工作原理像charm.with此u代码可以将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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM