简体   繁体   English

HTML-页面之间的cookie。

[英]HTML - cookies between pages.

I have a quiz in several HTML pages (I know it could be in only one but it has to be a page for question - q1, q2, q3...) with 4 radio buttons in each one (for q1: q1a, q1b, q1c, q1d; for q2: q2a, q2b, q2c, q2d, etc), and I want to set a cookie in each page with the name of the question (q1) and the checked answer (q1a, for example). 我在几个HTML页面中进行了一个测验(我知道它可能只在一个页面中,但必须是一个问题页面-q1,q2,q3 ...),每个页面中有4个单选按钮(对于q1:q1a,q1b) ,q1c,q1d;对于q2:q2a,q2b,q2c,q2d等),我想在每个页面中设置一个Cookie,其中包含问题的名称(q1)和已检查的答案(例如q1a)。 I have created this function to set a cookie: 我创建了此函数来设置Cookie:

function set_cookie ( name, value ) {
    var cookie_string = name + "=" + escape ( value );  
    document.cookie = cookie_string;
}

And I have put it in each page of the quiz. 我已将其放在测验的每一页中。 It works fine in each page, but when in the final page I use a function to get the cookies, it returns null. 它在每个页面上都能正常工作,但是在最后一页中,我使用一个函数获取Cookie时,它返回null。 The function I have is this one: 我具有的功能是这一功能:

function get_cookie ( cookie_name ) {
    var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
    if ( results )
        return ( unescape ( results[2] ) ) ;
    else
        return null;
}

But when I call this function with the function to make the final grade of the quiz, it returns null: 但是,当我将此函数与进行测验的最终成绩的函数一起调用时,它将返回null:

function grade () {
    var grade = 0;
    var x = get_cookie( "q1" );
    var y = get_cookie( "q2" );
    alert(x); //Just to see if the function works fine
    ...
    var xx = 0;
    var yy = 0;
    ...
    if(x == "q1a") xx = 20; //correct answer
    else xx = 0; //wrong answers

    if(y == "q2c") yy = 20; //correct answer
    else yy = 0; //wrong answers
    ...
    ...
    grade = xx + yy;
    alert("Your qualification is "+grade);
}

What am I doing wrong? 我究竟做错了什么? Is it not possible to get the cookies from one page in another one if both pages are in the same directory? 如果两个页面都在同一目录中,则不可能从一个页面中的另一页面获取cookie?

The best way would be to use local storage not cookies. 最好的方法是使用本地存储而不是cookie。 Check w 3 schools. 检查w 3所学校。

It is really simple to achieve and it can be carried throughout the pages 这确实很容易实现,并且可以在整个页面中进行

I hope that helps! 希望对您有所帮助!

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

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