Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

cookies - Remember preferable language

I've made a simple website for my daughter. It is in Dutch and for every page there is a English version as well.

Dutch URL: nl/index.html

English URL: eng/index.html

What I would like to do is give the visitor the option to set one language as preference. So if they come to this site the next time they will automatically linked to the preferable page. I know this can be done with a cookie and saw the explanation on this forum ( How to remember the currently clicked url? javascript?PHP? ).

I've tried to make this work but apparently I am doing something wrong? Can somebody guide me through step by step? That would be great!

Kind regards, Jurgen

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are familiar with jQuery you can use the cookies plug-in to persist the user's language choice and redirect him to the appropriate page every time he comes back to your site. Bellow is a sample code that uses two buttons to set the language:

First you declare the jQuery scripts (I use to store them in a Script folder, hence the following):

<script type="text/javascript" src="../Script/jquery-1.7.2.js"></script>
<script type="text/javascript" src="../Script/jquery.cookie.js"></script>

Then you define the page ready event like this:

$(function () {

    var url = 'your_url';
    var english_page = 'eng/index.html';
    var dutch_page = 'nl/index.html';

    if ($.cookie('default_page') != null) {
        if (window.location.href != url + '/' + $.cookie('default_page')) {
            window.location.href = url + '/' + $.cookie('default_page');
        }
    }

    $('#set_english_butt').click(function () {
        $.cookie('default_page', english_page, { expires: 999 });
        alert('English was set as the default language');
    });

    $('#set_dutch_butt').click(function () {
        $.cookie('default_page', dutch_page, { expires: 999 });
        alert('Dutch was set as the default language');
    });

});

Which is hooked to some html buttons in you page:

<div>
    <span>Select your language:</span>
    <button id="set_english_butt">English</button>
    <button id="set_dutch_butt">Dutch</button>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...