jquery cookie set value to boolean true

╄→гoц情女王★ 提交于 2019-11-30 08:33:26

问题


I am using this jquery.cookie plugin and I need to set value to TRUE or NULL/FALSE.

I am trying to do it like this: $.cookie('ff', true, { expires: 30, path: '/' }); but it sets the value to string and not boolean.

Any ways of fixing this?


回答1:


Cookies are only string-valued. As gdoron commented, if you want to treat the value as a boolean, you need to parse it back to a boolean when the cookie value is read back out.

Since you commented that you are reading the cookie value with PHP, see Parsing a string into a boolean value in PHP.




回答2:


Client side:

$.cookie('ff', "true", { expires: 30, path: '/' });

Server side:

$cookie = $this->input->cookie() == "true";

EDIT: Cookies are strings. Anything stored to cookies will need to be converted to strings. Hence you have to do the string to boolean conversion on the reading side of it. Above I have put an example for PHP (CodeIgniter).




回答3:


If you are just looking to use a cookie as a sort of flag, then just check if the cookie exists and if it does not you can assume it is false:

const isSet = Boolean(cookie.get('my-cookie')) || false

This way you don't need to even worry about the actual value of the cookie and just whether or not it exists.




回答4:


Another way to do this is

var mycookie = !($.cookie("cookiename")=='false')

Or:

if(!($.cookie("cookiename")=='false')){ 
    //mycode 
}

If the value is 'false' then ($.cookie("cookiename")=='false') will return true so we invert it by using ! which return false

if the value is not 'false' then it will return false so we invert it by using ! which return false



来源:https://stackoverflow.com/questions/9752442/jquery-cookie-set-value-to-boolean-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!