首页 > 解决方案 > 产品未在电子商务网站上显示

问题描述

我创建了电子商务网站。类别和品牌都显示成功。我的问题是如果我单击类别。产品应根据我点击的类别显示。示例:如果我单击电视作为一个类别,所有电视产品都应该显示。
就像我到目前为止所尝试的那样。我附上了下面的代码。当我运行编程并单击类别时,我收到错误为“未捕获的 ReferenceError:cid 未定义”

我为显示类别编写的这段代码,但所有类别都显示成功。

 $('#categories').append('<a href="#" cid= '+ id + '  class="list-group-item list-group-item-action">' + '<b>'+ data[i].catname + '<b>' + '</a>');

类别的完整代码

类别

  function getCategory(){
            $.ajax({
                type: 'GET',
                url: 'get_category.php' ,
                dataType: 'JSON',
                success: function (data)
                {
                    for (var i = 0; i < data.length; i++)
                    {
                        var catname = data[i].catname;
                        var id = data[i].id;

 $('#categories').append('<a href="#" cid= '+ id + '  class="list-group-item list-group-item-action">' + '<b>'+ data[i].catname + '<b>' + '</a>');
                    }
                },
                error: function (xhr, status, error)
                   {
                    console.log(xhr.message)
                }

            });
        }


                    }

当我单击类别时,应显示相关产品我写了下面的代码

$("#categories").click(function ()
{
$.ajax({
    type: 'post',
    url: 'get_product.php' ,
    data: {cid:cid},
    dataType: 'JSON',
    success: function (data) {
        console.log(data);

        for (var i = 0; i < data.length; i++)
        {
            var price = data[i].price;
            var image = data[i].image;
            var description = data[i].description;

            $("#Products").append("<div class='col-md-4'> " +
            "<div class='panel panel-info' id='Products'>" +
            "<div class='card-body'>" +
            "<div class='panel-heading'>"  +  "<h4> "  +  description + "</h4> " +
            "<p class='panel-body'>"+  "<h3> "  +  price + "</h3>" +
            "<p class='panel-body'> <img class='card-img-top' style='width:250px' height='250px' id='theImg' src='images/"  + image  + "' /> </p>" +
            " <a href='#' class='btn btn-primary'>View More</a> </div> </div></div> </div>");
        }
    },
    error: function (xhr, status, error) {
        alert(xhr.responseText);
    }
});
});

get_product.php 页面

<?php
include("db.php");
$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products where id = ? order by RAND() LIMIT 0,6");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);

$cid = $_POST["cid"];
$stmt->bind_param("s", $cid);


if ($stmt->execute()) {
    while ( $stmt->fetch() ) {
        $output[] = array ("id"=>$id, "cat_id"=>$cat_id,"brand_id"=>$brand_id,"price"=>$price,"description"=>$description,"image"=>$image,"keywords"=>$keywords);
    }
    echo json_encode($output);
}
$stmt->close();
?>

标签: phpjqueryjsonajax

解决方案


我认为这会给您带来错误,您需要获得点击的类别 ID

var cid = $(this).attr('cid'); // Use this and try
 data: {cid:cid},

推荐阅读