douqiaotong8682 2012-10-19 21:56
浏览 38

无法使用php设置cookie,然后使用javascript移动使用javascript读取它

I'm trying to use jquery mobile to create a simple web app. At one point in the app, I need to get information from a php page to a javascript page, and then back and forth again (i.e., javascript will update the cookie, which will be read by php, which will then be read by javascript, etc.).

In order to test that I could set a cookie with php and then read it with javascript on the same page load, I created the following, working script:

<?php
    include("../../../connectFiles/connect_dev.php");
    setcookie("cookie_test","hello", 0, '/');       
?>


<html>
    <head><title>Cookie setting test</title></head>
<body>
    <script type="text/javascript">
    function readCookie(name) {
        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) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    alert(readCookie('cookie_test'));
</script>
Hello there, I hope you were able to see my cookie!
</body>

As I mentioned, this worked just fine. However, when I take the same code and try and implement it inside of a jquery mobile framework, I can't seem to find the cookie. It keeps coming up as "null." I'm guessing this has something to do with when the cookie is being accessed through the jquery mobile framework. I've bound the readCookie function to the pageshow function in jquery mobile like this:

$(document).on('pageshow',function(e, ui){
if (e.target.id == 'assessment') {
    var objective = readCookie('objective');
    alert("objective: "+objective);

Unfortunately, this results in a "null" cookie value every time. What do I need to do to be able to set the cookie in PHP and call it in javascript?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
    • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥120 计算机网络的新校区组网设计
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据
    • ¥20 软件测试决策法疑问求解答
    • ¥15 win11 23H2删除推荐的项目,支持注册表等