简体   繁体   中英

How can I use JavaScript (AJAX/jQuery) to tell if a PHP $_SESSION cookie exists?

I am working on my PHP/MySQL server (website really just a PHP server), and I want to switch from PHP echoing to JavaScript writing something. I want this because the following reasons.

1: JavaScript is easier on my page, and

2: because for some reason PHP echoing breaks my navigation bar but JavaScript don't. Could I do something like this but tweak it to tell whether it DOES or DOESN'T exist?

THIS IS MY CODE:

<script>
document.cookie = "username='<?php echo $_SESSION['username'] ?>';";
var u = document.cookie;
document.getElementById("username").innerHTML = u();
</script>

for some reason PHP echoing breaks my navigation bar but JavaScript don't

This sounds like an issue we could probably fix if we had a sufficient amount of code and an example of the HTML source at runtime.

Regardless - and this is probably a lot less straightforward than echoing a variable - you could set a cookie in PHP and retrieve it in JavaScript with no inline PHP tags needed. Some example code:

PHP (read about setcookie ):

setcookie("username", $_SESSION['username']);

JavaScript (function from this SO answer ):

function getCookieValue(a) {
    var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b ? b.pop() : '';
}

var u = getCookieValue("username");

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.

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