获取“参数未定义”;在jQuery与AJAX, MySQL和PHP


Getting "Parameter undefined" in jQuery with AJAX, MySQL and PHP

我正在用PHP与mysqli数据库建立一个购物网站,我有一个"category""brands"部分在那。

我想要的是用户可以通过点击类别&在ajax jQuery的帮助下,无需页面刷新。

例如Category>Electronics,它会在网站主页上显示电子产品。

也许有了代码,会更清楚。

这是HTML的一部分:

        <div class="panel panel-info">
           <div class="panel-heading">Products</div>
            <div class="panel-body">
                <div id="getProduct"></div>
            </div>

这是"action.php"文件中的PHP代码:

    <?php
    if(isset($_POST["getSelectedCategory"])){
        $cid=$_POST["categoryID"];
        $sql="SELECT * FROM products WHERE productCat = '$cid' ";
        $run_query=mysqli_query($con, $sql);
        while($row=mysqli_fetch_arry($run_query)){
            $productID = $row["productID"];
            $productCat = $row["productCat"];
            $productBrand = $row["productBrand"];
            $productTitle = $row["productTitle"];
            $productPrice = $row["productPrice"];
            $productIMG = $row["productIMG"];
            echo " <div class='col-md-4'>
 <div class='panel panel-info'>
<div class='panel-heading'>$productTitle</div>
<div class='panel-body'>
 <img src='assets/$productIMG' style='width: 160px; height: 250px;'/>
   </div>
  <div class='panel-heading'>$productPrice.00$
    <button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>
      </div>
    </div>
     </div> ";
 }
}
?>
这是jQuery代码:
   $("body").delegate(".category","click",function (event) {
        event.preventDefault();
        var cid = $(this).attr("categoryID");
        /*Used this alert to see if the
         right category number is shown, Here it says undefined*/
        alert(cid);
       $.ajax({
            url: "action.php",
            method: "POST",
            data: {getSelectedCategory: 1, categoryID: cid},
            success: function (data){
                $("#getProduct").html(data);
            }
        })
    });

我在代码中找不到问题

您的js代码正在听.category类。在php代码模板中没有这样的类。这就是您的echo应该如何工作:

echo " <div class='col-md-4'>
         <div class='panel panel-info'>
           <div class='panel-heading'>$productTitle</div>
             <div class='panel-body'>
               <img src='assets/$productIMG' style='width: 160px; height: 250px;'/>
             </div>
             <div class='panel-heading'>
               <a class='category' categoryID = '$productCat'>$productBrand</a>
                $productPrice.00$
             <button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>
          </div>
        </div>
     </div> ";

看-我已经添加了<a class="category" categoryID = '$productCat'>$productBrand </a>到你的面板标题。

相关文章: