[英]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. 我正在使用
PHP/MySQL
服务器(网站实际上只是一个PHP服务器),并且想从PHP
回声切换为JavaScript
编写东西。 I want this because the following reasons. 我要这样做是因为以下原因。
1: JavaScript is easier on my page, and 1:JavaScript在我的页面上更简单,并且
2: because for some reason PHP echoing breaks my navigation bar but JavaScript don't. 2:因为某些原因,PHP回显会破坏我的导航栏,但JavaScript不会。 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
由于某些原因,PHP echo破坏了我的导航栏,但是JavaScript没有
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. 这听起来像是一个问题,如果我们在运行时拥有足够的代码量和HTML源代码示例,则可以解决。
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. 无论如何-与回显变量相比,这可能要简单得多-您可以在PHP中设置cookie,而无需使用内联PHP标签就可以在JavaScript中检索它。 Some example code:
一些示例代码:
PHP (read about setcookie ): PHP(了解setcookie ):
setcookie("username", $_SESSION['username']);
JavaScript (function from this SO answer ): JavaScript( 此SO回答的功能):
function getCookieValue(a) {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
}
var u = getCookieValue("username");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.