I have a cookie named myName
In php, to print the cookie value, I can simply do
<?=$_COOKIE['myName']?>
The shortest I have found in JS is:
<script>
document.write($.cookie('myName'));
</script>
Is there not a better/shorter way to do this? Maybe with JQuery?
I am quite new to JS and moving a site over from PHP for mobile Phonegap Build dev so can't use PHP
您可以使用jQuery Cookie插件( http://plugins.jquery.com/cookie/ )来获取Cookie,就像
$.cookie("myName")
If you don't want to use a plugin like jQuery $.cookie, you can do something like this
function getCookie(cookiename) {
var cookiestring = RegExp(""+cookiename+"[^;]+").exec(document.cookie);
return unescape(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
var value = getCookie('myName');
And what you will find very usefull is to use the console while debugging: write in your code: console.log(document.cookie);
or
console.log($.cookie('myName'));
And see the results in the javascript console of your browser (easiest way: right click in your page, go to the last item which says "inspect element", and in the window that will open, go to the last tab, named "console".)
use a self executing function
<script>
(function(){document.cookie="username=test; expires=Fri, 28 Feb 2014 12:00:00 GMT; path=/";})();
</script>
check out more information on MDN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.