Итак, я пытаюсь сохранить и загрузить файл cookie, содержащий список сведений о продукте, а затем отобразить эти сведения о продукте на странице.
Однако, когда я запускаю это, я получаю
ReferenceError: Не могу найти переменную: GetProductPrice
при попытке прочитать файлы cookie, которые ясохраняется с помощью функции GetProductPrice()
.
Хранитель файлов 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;
}
}
}