Pergunta

This script creates a cookie depending on form data, (ex: ?docname=My Document)

<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
    var save = getValue("save");
    var url = window.location.href;
}
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
function saveDoc() {
    if (docname != '') {
        setCookie(docname,url,730);
    }
    else {
     // Nothing else to do
    }
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
    var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
    alert(errorText);
}
</script>

It creates the cookie and sets the name of it as the docname variable, but when it sets the url as the value, it cuts off the form data.

I've researched and changed the code but couldn't find an answer, can anyone help?

Solution

<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
    var save = getValue("save");
    var url = window.location.href;
    var recode = encodeURIComponent(url);

}
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
function saveDoc() {
    if (docname != '') {
        setCookie(docname,recode,730);
    }
    else {
     // Nothing else to do
    }
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
    var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
    alert(errorText);
}
</script>

changed the variable used to set the value to recode and set recode equal to encodeURIComponent(url); so it decodes the url, decoding it and making it possible to have form data in a value or name of a cookie, etc. Thanks to @epascarello

Foi útil?

Solução

encodeURIComponent() is your friend here

document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";

and when you get it, you need to decode it with decodeURIComponent().

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top