具有Firebase实时数据库的购物车JS

时间:2019-07-02 19:27:54

标签: javascript html firebase firebase-realtime-database

我正在尝试使用香草JS创建购物车。该项目看起来应类似于THIS,但必须将项目发送到Firebase实时数据库,并且该应用程序必须为CRUD。 firebase数据库链接为this。我已经插入了到目前为止的工作。我已经用我的Firebase数据库中的数据创建了一个动态表。

我该怎么做,以便当我单击“添加到购物车”时,用户选择的项目保存在数据库的购物车对象中?因为在创建要显示它们的结帐页面时,我将需要检索它们。另外,使用物品的库存,当我向购物车中添加物品时,必须在firebase中修改拣配物品的库存。因此,如果商品的库存为300,并且用户将商品添加到购物车100,则火力储备必须显示剩余的库存商品。我该怎么办?

let getUrl = new URL(document.URL);
let firebaseId = getUrl.searchParams.get('id');

productData()
    .then(response => {
        if (response.status === 200)
            return response.json();
        else
            console.log(response.status);
    })
    .then(function (data) {
        product = data;
        drawDetails();
    })
    .catch(err => console.log(err));

function productData() {
    return fetch(`https://proiect-final-f676e.firebaseio.com/phones/${firebaseId}.json`, {
        method: 'GET'
    });
}


function drawDetails() {
    var html = `
    <div class="card" style="width: 50rem;">
    <img src="${product.image}" class="card-img-top">
    <div class="card-body">
    <h2 class="card-title">${product.name.toUpperCase()}</h2>
    <p class="card-text"><b>Description:</b>&nbsp${product.configuration}</p>
    </div>
    <ul class="list-group list-group-flush">
    <li class="list-group-item"><p><b>Price:</b>&nbsp${product.price}</p>
    </li>
    <li class="list-group-item"><p><b>Stock:</b>&nbsp${product.stock} items</p></li>
    </ul>
    <div class="card-body">
    <a href="#" class="card-link"><button class="bag-btn" data-id=${product.id} onclick="addToCart();"><i class="fas fa-shopping-cart">&nbspAdd to cart</i></button></a>
    </div>
    </div>
    `;
    document.querySelector('#content').innerHTML = html;
}

function ajax(method, url, body) {
    return new Promise(function (resolve, reject) {
        let xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(JSON.parse(this.responseText));
                } else {
                    reject(new Error("serverul a dat eroare"));
                }
            }
        };
        xhttp.open(method, url, true);
        xhttp.send(body);
    });
}

var url = "https://proiect-final-f676e.firebaseio.com/"
async function addToCart(id, quantity) {
    var arr = await Promise.all([
        await ajax("GET", url + "cart/" + id + ".json"),
        await ajax("GET", url + "phones/" + id + "/stock.json")
    ]);
    var cartQuantity = arr[0];
    var stock = arr[1];


    var cartQuantity = await ajax("GET", url + "cart/" + id + ".json");
    var stock = await ajax("GET", url + "phones/" + id + "/stock.json");

    if (cartQuantity === null) {
        cartQuantity = 0;
    }
    console.log(quantity, cartQuantity, stock);
    if (stock < quantity + cartQuantity) {
        quantity = stock;
    } else {
        quantity = quantity + cartQuantity;
    }
    await ajax("PUT", url + "cart/" + id + ".json", quantity);
}
* {
  outline: none;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

body {
  min-width: 476px;
}

header {
  background-color: black;
  width: 100%;
  height: 70px;
  font-size: 25px;
  color: white;
  position: relative;
  padding: 15px;
  overflow: hidden;
  min-width: 478px;
}
.button {
  float: right;
  font-size: 20px;
  color: white;
  border: none;
  background-color: black;
  width: 60px;
  right: 0;
  top: 0;
  box-sizing: border-box;
  text-transform: uppercase;
}

#textAnimation {
  font-size: 20px;
  color: white;
  border: none;
  background-color: black;
  width: 170px;
  display: inline-block;
  text-align: center;
}
#textAnimation span {
  cursor: pointer;
  display: inline-block;
  position: relative;
  transition: 0.5s;
}

#textAnimation span:after {
  content: "Categories";
  opacity: 0;
  top: 0;
  right: -20px;
  transition: 0.5s;
}

#textAnimation:hover span {
  padding-right: 25px;
}

#textAnimation:hover span:after {
  opacity: 1;
  right: 0;
}

#textAnimation:hover {
  color: lightgrey;
}

.button:hover {
  color: rgb(204, 197, 197);
}

img {
  width: 50%;
  height: auto;
}


.card{
  margin: 50px auto auto auto;
  border:1px solid lightgray;
  padding:10px;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Online Shop</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://kit.fontawesome.com/2926c10e78.js" defer></script>    
</head>

<body>
    <div id="header">
        <header>
            <a href="index.html" style="text-decoration: none; color:white"><span><i class="fab fa-apple"></i>&nbspApple
                    Store</span></a>
            <button class="button">
                <i class="fas fa-shopping-cart"></i></button>
            <button class="button">
                <i class="fas fa-lock"></i><span></span></button>
            <a href="index.html"><button class="button" id="textAnimation"><span></span><i
                        class="fas fa-stream"></i></span></button></a>
        </header>
    </div>
    <a href="./phones.html" class="card-link"><button id="back">Back to the phones</button></a>
    <div id="content">
    </div>

</body>

</html>

0 个答案:

没有答案