我在寻找自昨天以来解决这个问题,我知道有很多类似的教程,但不知何故,他们没有为我的情况工作。在for循环中设置cookie
我想要做的是设置cookie,每当用户点击任何产品(它应该存储product_id)。所以这个产品将被添加到图表中。
我检查了Chrome浏览器的javascript控制台,但有一个奇怪的错误“Uncaught SyntaxError:Unexpected token}”,它说没有任何存储的cookie。
echo "<div id='products'>";
for($i=0;$i<$num;$i++)
{
$ftc = mysql_result($result, $i, "product_image");
$ftc2 = mysql_result($result, $i, "product_id");
$ftc3 = mysql_result($result, $i, "product_name");
$ftc4 = mysql_result($result, $i, "product_preis");
$ftc5 = mysql_result($result, $i, "product_old_preis");
echo "<a href='details.php?product=".$ftc2."'>
<div class='products_list'>
<img width='217px' height='323px' src='".$ftc."'/>
<div class='alt_yazi2'><b>".$ftc3 ."  
<font style='float:right;'>".$ftc4."TL  <b style='text-decoration:line-through; float:right;'>".$ftc5."TL </b></font></b></a>
</br>
<div id='sepet'><a onclick='setCookie('ccname', '".$ftc2."', 'expiry');' href='#'>
<img width='35px' height='25px' src='images/cart_icon.png'/>
</a>
</div>
</div></div> ";
}
echo "</div> ";
?>
而且这段JavaScript代码是在页面头部:
<script type="text/javascript" >
// JavaScript Document
var today = new Date();
var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal (j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function DeleteCookie (name,path,domain) {
if (GetCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
</script>
在此先感谢
在任何体面的浏览器中,它都会告诉你它到底在哪里遇到错误(代码的行数)。这些信息通常非常有帮助。 – jfriend00 2012-01-09 15:12:55
也请将'onclick ='setCookie('ccname',''。。$ ftc2。'','expiry');''改为'onclick ='setCookie('ccname','“。$ ftc2。 ', '到期');返回false'' – mplungjan 2012-01-09 15:16:36
它似乎也运行在jsfiddle上:http://jsfiddle.net/ufSs3/1/ – user823255 2012-01-09 15:17:56