草庐IT

javascript - 存储和调用 cookie Javascript 的问题

coder 2024-05-16 原文

因此,我试图保存并加载一个包含产品详细信息列表的 cookie,然后将这些产品详细信息显示到页面上。

然而,当我运行这个时,我收到的是一个

ReferenceError: Can't find variable: GetProductPrice

尝试读取我使用 GetProductPrice() 函数存储的 cookie 时。

Cookie 存储程序在网站首次加载时运行。它创建了一个产品列表,我稍后打算将其用作购物车的一部分。然后它应该保存这个 cookie,以便在用户转到不同页面时可以再次访问它。这样,如果用户将商品添加到购物车,购物车变量将不会在以后重置。但是正如我之前所说,这是行不通的。加载和保存 cookie 函数是由其他人在 Stack Overflow 上创建的,并且工作正常。

这是 cookie 保护程序的代码,它应该只在用户第一次访问网站时运行:

function setUpProducts() { //in here we define each of the products when we first start up. This way we know what products the customer has access to.
  setUpPages();
  try {
    hasRun = getCookie('hasRunCookie'); //get the has run cookie from before, or at least try to
  } catch {
    hasRun = 0;
  }
  //if (hasRun != 1){ //only run this the first time, otherwise we dont need to.
  if (hasRun != 1) {
    hasRun = 1;
    createCookie('hasRunCookie', hasRun);
    var dataList = []; //array for holding the raw data
    var nameList = [];
    var priceList = [];
    var amountList = []; //lists for temporrily holding data before it is put in the product list's product objects.
    var set1 = 0; //allows differentiating between different values in the raw data
    var productIds = 0; //product ID to differentiate between products easily

    $.get('../productdata.txt', function(data) { //the text file product data contains all the product infomation so that it can be changed at a moments notice.
      //var fileDom = $(data);

      dataList = data.split("\n");
      $.each(dataList, function(n, elem) {
        $('#myid').append('<div>' + elem + '</div>');
      });
    });

    var i;
    for (i = 0; i < dataList.length; i++) { //this gets the infomation from the text file and loads it into the products
      if (set1 == 0) {
        nameList.push(dataList[i]);
        set1 = 1;
      } else if (set1 == 1) {
        priceList.push(dataList[i]);
        set1 = 0;
      }
    }
    while (productIds != 8) { //make the products, programing counting always starts at 0, so 8 is actually the 9th number.
      var productObject = {
        productID: productIds,
        productName: nameList[productIds],
        productPrice: priceList[productIds],
        purchasedAmount: 0
      };
      productList.push(productObject); //put each product into the product list.
      productIds += 1;
    }
    var json_str = JSON.stringify(productList); //bottle and store our list of products
    createCookie('ProductListCookie', json_str);
    //}

  }

这是用于加载 cookie 并在相关产品页面上显示产品价格的代码:

function GetProductPrice(productIdz) {
  var json_str = getCookie('hasRunCookie');
  productList = JSON.parse(json_str);
  for (i = 0; i < productList.length; i++) {
    if (productList[i].productID == productIdz) {
      productHolder = productList[i];
      document.getElementById("price").innerHTML = productHolder.productPrice;
    }
  }
}

最佳答案

使用localStorage

//Set
localStorage.setItem('ProductListCookie', json_str);

//Get
var json_str = localStorage.getItem('ProductListCookie');

关于javascript - 存储和调用 cookie Javascript 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50557862/

有关javascript - 存储和调用 cookie Javascript 的问题的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  4. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  5. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  6. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  7. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  8. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  9. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  10. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

随机推荐