2016-07-10 3 views
1

쿠키에 변수를 저장하고 검색하려고합니다. 지금까지 텍스트 및 페이지 URL 만 저장하고 원하는 위치에서 검색 할 수 있습니다.쿠키에서 변수를 찾고 저장하십시오.

도와 주실 수 있습니까? 예를 들어,이 코드에서 $ room 및 $ renthome 값을 쿠키에 저장하려고합니다. $.cookie('name', 'value');

retri :

이 내 현재 코드

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title>New page string name</title> 
 
    <link rel="stylesheet" href="css/reset.css"> <!-- Resource style --> 
 
<link rel="stylesheet" type="text/css" href="css/buy-rent.css" /> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 
 
    <script> 
 
    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(); 
 
    }); 
 

 

 
    var myfaves = JSON.parse(readCookie('favespages')); 
 
    if(myfaves){ 
 
     faves = myfaves; 
 
    } else { 
 
     faves = new Array(); 
 
    } 
 

 
    }); 
 
    </script> 
 
</head> 
 
<body> 
 
    <a href="javascript:void(0);" id="addTofav">Add me to fav</a> 
 
    <div class="img"> 
 
    <div class="desc"> 
 
    <ul id="appendfavs"> 
 
    
 
    </ul> 
 
    </div> 
 
    </div> 
 
<?php 
 
error_reporting(0); 
 

 
include("config.php"); 
 

 
$quer= "SELECT*FROM ".$db_table." "; 
 

 

 
$query=mysqli_query($connect,$quer) 
 
or die(mysqli_error()); 
 
?> 
 

 
<?php while($row = mysqli_fetch_array($query)): 
 
$idhome= $row['idhome']; 
 
$room=$row['room']; 
 
$renthome=$row['renthome']; 
 
$pricehome=$row['pricehome']; 
 
?> 
 

 
<?php endwhile;?> 
 

 
</body> 
 
</html>

답변

0

이다 나는 jQuery를 쿠키

https://github.com/carhartl/jquery-cookie

사용을 사용 eving : 수행 쿠키에 복잡한 데이터를 저장하기 위해 $.cookie('name'); // => "value"

다음은 :

1) 오브젝트의 전체 데이터를 저장합니다. var cookieData = {};처럼 뭔가 한 다음 cookieData.date = yourDate; cookieData.myUrl=yourUrl;

이 같은 property는 추가 할 수 있습니다)는 쿠키에 문자열을 저장) JSON.stringify

3 사용하여 함정 수사에 개체를 전송합니다.

이제 위해 다시 사용 -

1) 쿠키를 검색())

2 위의 코드를 참조

3 JSON.parse를 사용하여 개체에 다시 문자열을 돌려) 가져 오기 객체로부터 원하는 데이터

+0

귀하의 답변에 감사하지만 u는 내 질문을받지 못했다고 생각합니다. 쿠키 이름이나 값을 정의하는 데 문제가 없습니다. 내 코드를 단순화하기 위해 그 부분을 삭제했습니다. u가 쿠키에있는 다른 변수를 모두 저장하고이를 검색하려고합니다.내가 그랬던 것처럼 페이지 제목. 나는 내 코드를 편집 해 주시길 바랍니다. 다시 한번 감사드립니다. – Malekian

+0

질문이 있습니다. 어떻게 오브젝트에 여러 변수를 저장할 수 있습니까? var cookieData = {$ idhome, $ room, $ renthome}; – Malekian

+0

어떤 매개 변수를 저장 하시겠습니까? – Roysh

0

jQuery에서는 jquery.cookie 플러그인을 사용해야합니다.

이 쿠키를

$.cookie(name, value [, options]); 

를 만든 다음이

$.cookie(name); 
+0

답변 해 주셔서 감사합니다. 문제. 쿠키 이름이나 값을 정의하는 데 문제가 없습니다. 내 코드를 단순화하기 위해 그 부분을 삭제했습니다. u가 쿠키에있는 다른 변수를 모두 저장하고이를 검색하려고합니다. 내가 그랬던 것처럼 페이지 제목. 나는 내 코드를 편집 해 주시길 부탁드립니다. 다시 한번 감사하십시오. – Malekian

0

당신은 PHP에서 변수를 저장합니다 <script> 블록을 생성 할 수있는 가치를 검색 할 수 있습니다. 예 : room이라는 쿠키를 $room 값으로 저장하는 것을 보여줍니다.

<script> 
    createCookie("room", "<?= $row['room'] ?>", 2); 
</script> 

다른 방법은 PHP로 쿠키를 설정하는 것입니다.

<?php setcookie("room", $row['room'], 2 * 24 * 60 * 60 * 1000); ?> 

PHP로 쿠키를 설정하려면 yhou이 출력을 보내기 전에해야한다는 것을 잊지 마십시오. 귀하의 경우에는 출력을 준비하고 쿠키를 설정 한 다음 출력을 보내야합니다.

+0

안녕하세요. 감사합니다. 데이터베이스에서 변수의 값을 얻었습니다. 이처럼 위의 질문을 바꿀 수 있습니까? – Malekian

+0

' – Malekian

+0

맞지 않습니다. 첫 번째 매개 변수는 쿠키 이름이고, 두 번째 매개 변수는 값입니다. 대답은 업데이트됩니다. – Misaz

관련 문제