简体   繁体   English

如何从PHP到javascript获取cookie?

[英]How do I get a cookie from PHP to javascript?

I'm having trouble getting a non-null response from my readcookie function in Javascript. 我无法从Javascript中的readcookie函数获取非空响应。 Ideally I would get a boolean response as to whether an id exists in my database or not, but currently it's only coming up with null. 理想情况下,我会收到关于ID是否存在于我的数据库中的布尔响应,但目前它只带有null。 I've had a look into the stored cookies and the IDFound cookie is not stored at all. 我已经查看了存储的cookie,而IDFound cookie根本没有存储。

Javascript side: JavaScript方面:

function readCookie(name) {
    $.get("/test/phpServerGet.php","function(result){}")
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0){ console.log("found")
        return c.substring(nameEQ.length,c.length)};
    }
    return null;
}

PHP: PHP:

<?php
require_once 'path_to_db_connect.php';
$id_exists = false;
$CollegeID = $_COOKIE["CollegeID"];
echo $CollegeID;
$request = $connect->prepare("SELECT `CollegeID` FROM `users` WHERE `CollegeID` = ?;");
$request->execute(array($CollegeID));
$result = $request->fetch(PDO::FETCH_ASSOC);
$cookie_name = "IDFound";
if ($result['CollegeID'] == $CollegeID)
{   echo "YES";
        $id_exists = true;
}

else if ($result['CollegeID'] != $CollegeID)
{
        $id_exists = false;
}
setcookie($cookie_name, $id_exists, 1000);
?>

PHP set cookie PHP设置cookie

setcookie($cookie_name, $id_exists, 1000);

the 3 argument is set to 1000, try replacing that with 3参数设置为1000,请尝试将其替换为

time() + 60 
setcookie($cookie_name, $id_exists, time() + 60);

That should give the browser more time to find the cookie and parse it. 那应该给浏览器更多的时间来查找cookie并对其进行解析。 time() + 60 will be one min. time()+ 60将是一分钟。

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

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