简体   繁体   English

如何存储并检索Cookie中图像的链接?

[英]How do I store and then retrieve a link to an image in a cookie?

I would like to be able to show a user a picture from one form page to the next. 我希望能够向用户显示从一个表单页面到下一页的图片。 The picture will be dynamic based on what he or she is doing. 图片将根据他或她的行为而动态变化。 So, I need to store the path link to that image in a cookie and then load that image on the next page. 因此,我需要将指向该图像的路径链接存储在Cookie中,然后在下一页上加载该图像。

How do I do that? 我怎么做?

Check the plugin: https://github.com/carhartl/jquery-cookie 检查插件: https : //github.com/carhartl/jquery-cookie

and then do: 然后执行:

$.cookie("img", img_url);

[OR] [要么]

You can set and get cookie using these functions: (From Quirksmode ) 您可以使用以下功能设置和获取Cookie:(从Quirksmode

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = escape(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 unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}

Use document.cookie to set and get the image URLs. 使用document.cookie设置并获取图像URL。

check this cite for details: w3Schools 检查此引用以获取详细信息: w3Schools

It shows that you didn't do much research on this simple thing. 它表明您对这个简单的东西没有做太多的研究。

Here's a very simple JSFiddle: fiddle 这是一个非常简单的JSFiddle: 小提琴

// Assign the cookie
document.cookie = "imgpath=/your/image.png";
alert(document.cookie);

// Use a regular expression to get the path from the entire cookie string. Sanitizations are left up to you.
var imgPath = /imgpath=([^;]+)/i.exec(document.cookie)[1];
alert(imgPath);

I suggest using the jQuery.cookie plugin mentioned in the other answers though, no need to make it any harder than it already is. 我建议使用其他答案中提到的jQuery.cookie插件,无需使其变得比现在更难。

Here is the regular expression explained: http://regex101.com/r/qH6rB5/1 - it shows how the actual value you are interested in, is captured. 以下是解释的正则表达式: http : //regex101.com/r/qH6rB5/1-它显示了如何捕获您感兴趣的实际值。

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

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