简体   繁体   English

相当于Javascript / jquery的echo(PHP)Cookie值

[英]Javascript/jquery equivalent of echoing (PHP) cookie value

I have a cookie named myName 我有一个名为myName的cookie

In php, to print the cookie value, I can simply do 在php中,要打印Cookie值,我只需

<?=$_COOKIE['myName']?>

The shortest I have found in JS is: 我在JS中找到的最短的是:

<script>
    document.write($.cookie('myName'));
</script>

Is there not a better/shorter way to do this? 有没有更好/更短的方法来做到这一点? Maybe with JQuery? 也许使用JQuery?

I am quite new to JS and moving a site over from PHP for mobile Phonegap Build dev so can't use PHP 我是JS的新手,并且将网站从PHP移至移动Phonegap Build开发人员,因此无法使用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 如果您不想使用类似jQuery $ .cookie的插件,则可以执行以下操作

function getCookie(cookiename) {
    var cookiestring = RegExp(""+cookiename+"[^;]+").exec(document.cookie);
    return unescape(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}

var value = getCookie('myName');

FIDDLE 小提琴

And what you will find very usefull is to use the console while debugging: write in your code: console.log(document.cookie); 您会发现非常有用的是在调试时使用控制台:输入您的代码:console.log(document.cookie);

or 要么

console.log($.cookie('myName')); 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".) 并在浏览器的JavaScript控制台中查看结果(最简单的方法:右键单击页面,转到最后一个显示“检查元素”的项目,然后在打开的窗口中转到最后一个选项卡,命名为“控制台” “)。

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 查看有关MDN的更多信息

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

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