Смысл вопроса создал простою страницу с списком товаров, названим, описанием, эта тянется с json через XMLHttpRequest. При клике выводиться название купленного товара, и меняеться счетчик (типа куплен 1). Для всего этого поднял простой node server. Это всё работает. Но мне ещё нужно чтоб значение этого счётчика сохранилось в это json. Чтоб когда я открою страницу в следующий раз это значение было уже изменённое. Всё наверно просто... Опишу ход моих мыслей -Добавить поле в json файл для количества продуктов.(done) -Дописать чтоб это значение загружалось с json(done) -Написать функцию чтоб по клику это значение перезаписывалось
И тут у меня ничего не выходит, подскажите как это сделать. PS: Это мой первый опыт с nodejs.
https://github.com/dedn/node.git
http://dedn.github.io/task3/
скрипт
(function () {
var buttons = document.querySelector('#list');
// попытки сохранить
// var file = '/data/product.json';
// var event = {
// name: "",
// description: "",
// value: 15
// };
//
buttons.onclick = function (e) {
var target = e.target;
if (target.tagName != 'BUTTON') return;
var product = target.closest('li').querySelector('.product-item__title').textContent;
alert(' You have bought a ' + product);
var count = target.closest('li').querySelector('.product-item__counter');
count.innerText = parseInt(count.innerText) + 1;
// var str = JSON.stringify(event);
// fs.writeFileSync('/data/product.json', str);
// jsonfile.writeFile(file, event, function (err) {
// console.error(err)
// });
};
var container = document.querySelector(".products-list");
getProduct();
function renderProduct(item) {
item.forEach(function (product) {
var element = getElementFromTemplate(product);
container.appendChild(element);
});
}
function getProduct() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data/product.json');
xhr.onload = function (evt) {
var rawData = evt.target.response;
var loadedProduct = JSON.parse(rawData);
renderProduct(loadedProduct);
};
xhr.send();
}
function getElementFromTemplate(data) {
var template = document.querySelector('#template');
if ('content' in template) {
var element = template.content.children[0].cloneNode(true);
} else {
var element = template.children[0].cloneNode(true);
}
element.querySelector('.product-item__title').textContent = data.name;
element.querySelector('.content').textContent = data.description;
element.querySelector('.product-item__counter').textContent = data.value;
return element;
}
})();
сервер
var fs = require('fs');
var jsonfile = require('jsonfile')
var data = fs.readFileSync('website/data/product.json');
var product = JSON.parse(data);
console.log(product);
console.log('start');
var express = require('express');
var app = express();
var server;
server = app.listen(3001, listening);
function listening() {
console.log("listening...");
}
app.use(express.static('website'));
// in progress
app.get('/website', addValue);
function addValue(request, response) {
var data = request.params;
var value = Number(data.value);
var reply;
values[value] = value;
var data = JSON.stringify(values, null, 2);
fs.writeFile('website/data/product.json', data, finished);
response.send(reply);
}
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>JsTask</title>
</head>
<body>
<div class="container">
<h1 class="title">Product List</h1>
<ul class="products-list" id="list"></ul>
</div>
<template id="template" style="display: none">
<li class="product-item">
<span class="product-item-img">
<img src="img/buy.jpg" alt="buy">
</span>
<h2 class="product-item__title"></h2>
<p class="content"></p>
<button class="product-item__buy-btn">Buy</button>
<span class="product-item__counter"></span>
</li>
</template>
<script src="script.js"></script>
</body>
</html>
json
[
{
"name": "Product",
"description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci aliquam atque corporis dignissimos eveniet minus molestiae nulla, officia, perferendis perspiciatis quam quasi qui quidem, similique temporibus? Ducimus necessitatibus repudiandae vero.",
"value": 0
},
]
Современные инструменты для криптотрейдинга: как технологии помогают принимать решения
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости