window.location结果为null

问题描述 投票:0回答:2

我想建立一个从数据库返回产品的网站,当点击“查看更多”时,应该从另一个html页面的服务器返回产品详细信息。问题是当我点击查看更多时,产品ID%20 =%20null :(。 productDetails =第二个html页面。 productDetails = div - 在index.html中从服务器返回产品

<script>
var productsUrlList = 'https://finalonlineshop.firebaseio.com/.json';
async function getProductsFromServer() {
    var productsResponse = await fetch(productsUrlList)
    var products = await productsResponse.json();
    return products;
}

async function showProducts(productsPromise) {
    var products = await productsPromise;
    var generatedHTML = '';
    var productsIDs = Object.keys(products);
    productsIDs.forEach(productID => {
        var product = products[productID];
        generatedHTML += getGeneratedHTMLForProduct(productID, product);
    });
    document.getElementById('categories').innerHTML = generatedHTML;
}

function getGeneratedHTMLForProduct(productID, product) {
    var generatedHTML = `
        <div id = categoriesDiv>
            <img class = "categoryImage" src = ${product.Image} />
            <div class = "categoryName">${product.Name}</div>
            <div class = "categoryPrice">$ ${product.Price}</div>
            <br>
            <button id = "seeMore" onclick = "seeMore('${productID}')">See 
    more</button>
        </div>
    `;
    return generatedHTML;
}

function seeMore (productID) {
    window.location = `./productDetails.html?productID = ${productID}`;//issue
}
function getProductIDFromUrl () {
var params = new URLSearchParams(window.location.search);
var productID = params.get('productID');
return productID;
}

async function getDetailsFromServer(productID) {
var detailsResponse = await fetch(`https://finalonlineshop.firebaseio.com/Products/details/${productID}.json`);
var details = await detailsResponse.json();
return details;
}

async function seeDetails(detailsPromise) {
var details = await detailsPromise;
var generatedHTML = `
    <div id = "detailsAboutProduct">
        <img src = "${details.Image}" /> //Cannot read property "Image" of null
        <div>${details.Name}</div>
        <div>${details.Details}</div>
        <div>$ ${details.Price}</div>
        <div>${details.Qty}</div>
        <button id = "addToCart" onclick = "addToCart();">Add to 
    cart</button>
    </div>
`;
document.getElementById('details').innerHTML = generatedHTML;
}

</script>
javascript firebase dom firebase-realtime-database
2个回答
1
投票

摆脱URL中=周围的空间,编码为%20。您还应该使用encodeURIComponent()来转义产品ID中的任何特殊字符。

function seeMore (productID) {
    window.location = `./productDetails.html?productID=${encodeURIComponent(productID)}`;
}

0
投票

您对firebase应用程序的查询似乎是错误的。

你是谁:https://finalonlineshop.firebaseio.com/Products/details/${productID}.json返回null

但你必须获取:https://finalonlineshop.firebaseio.com/${productID}.json而它将返回正确的对象

© www.soinside.com 2019 - 2024. All rights reserved.