【问题标题】:How to tell ajax to get the selected data and retrive a data from the database acquired to the selected data如何告诉ajax获取选中的数据并从数据库中检索一个数据获取到选中的数据
【发布时间】:2018-04-03 20:34:32
【问题描述】:

我有 2 个选择框。第一个是选择品牌,第二个是选择产品。我想要的是第二个选择框从数据库中获取与第一个选择框具有相同品牌名称的数据。我对 AJAX 没有任何线索。我从朋友那里得到了这个脚本,但它不起作用...... 我的数据库是什么样的:

“品牌”数据库:

brand_id | brand_name
    1    | ADIDAS
    2    | NIKE

这是我的“产品”数据库:

product_id | brand_name | product_name | product_image | amount | sell | buy
     1     |   ADIDAS   |    T-Shirt   |     none      |   50   |  30  | 28
     2     |   NIKE     |    Shoes     |     none      |   20   |  130 | 120

这是我的代码:

<!DOCTYPE html>
<html>
<head>
  <title>TEST | INDEX</title>
  <meta charset="utf-8" lang="en">
  <script src="ajax.js"></script>
</head>
<body>
  <select required="required" name="brand_name">
    <option disabled selected>----SELECT----</option>
    <?php 
      require_once 'connections/dbc.php';
      $query = "SELECT `brand_name` FROM `brands`";
      $response = @mysqli_query($conn, $query);
      if (!$response) {
        $_SESSION['errortitle'] ='Error loading the brands';
        $_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
        header("location: error.php");
        exit();
      } else {
        while($row = mysqli_fetch_array($response)){
          echo '<option value='.$row['brand_name'].'>'.$row['brand_name'].'</option>';
        }
      }
    ?>
  </select>
<select required="required" name="product_name" disabled>
  <option disabled selected >SELECT</option>
    <?php

    ?>
</select>
<script>
    $('[name = "brand_name"]').change(function(event){
        var brand_name = $(this).val();
       $.get( 
          "action/ajax.php",
          { brand_name: brand_name },
          function(data) {
            var opts = $.parseJSON(data);
                $.each(opts, function(i, d) {
                    $('[name="product_name"]').append($('<option>', {
                        value: d.product_name,
                        text : d.product_name
                    }));
                });
                //Enable the product_name select box
                $('[name="product_name"]').prop('disabled', false);
                //Refresh the product_name select box
                $('[name="product_name"]').selectpicker('refresh');
          }
       );
    });
</script>

</body>
</html>

这里是 ajax.php 代码:

<?php
    require_once '../connections/dbc.php';

    $getBrandName = $_REQUEST['brand_name']; // This is the id of the selected brand name
    $query = "SELECT 'product_name' FROM `product` WHERE brand_name = '$getBrandName' ";
    $response = @mysqli_query($conn, $query);
    if (!$response) {
        echo "Error loading the prouducts";
        echo 'Something wrong happend while loading the proudcts.<br/>Please contact The developer';
        exit();
    } else {
          while($row = mysqli_fetch_array($response)){
            $productsArray[]['name'] = $row['product_name'];
        }
        echo json_encode($brandName);
    }
 ?>

【问题讨论】:

  • 当你说它不起作用时,什么不起作用?在这里提供更多信息会很好。
  • 如果我理解正确,您希望根据第一个下拉菜单的选择来填充第二个下拉菜单?
  • 您在浏览器的开发工具中得到任何响应吗?在 Chrome 中单击 F12,单击网络选项卡并仅过滤 XHR 类型。检查并查看此处返回的状态代码。如果是 200,那么您可能正在获取数据并且问题出在 JavaScript。如果您返回 400 或 500 代码,则问题可能出在服务器端。
  • @webdevsoup 不起作用的是,在从第一个框中选择数据后,我在第二个选择框中没有得到任何数据####### 请注意,第二个框变成了从第一个框中选择数据后可用,这意味着 JavaScript 是对脚本的响应,在选择后被告知要启用它........
  • @ObsidianAge 是的,就像我在阿迪达斯设置品牌一样,第二个框必须显示我唯一具有相同品牌名称的产品

标签: javascript php jquery ajax mysqli


【解决方案1】:

试试这个:

<?php
require_once 'connections/dbc.php';

// Get our brands
$query = "SELECT `brand_name` FROM `brands`";
$response = @mysqli_query($conn, $query);
if (!$response) {
    $_SESSION['errortitle'] = 'Error loading the brands';
    $_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
    header("location: error.php");
    exit();
} else {
    $brands = mysqli_fetch_array($response);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>TEST | INDEX</title>
    <meta charset="utf-8" lang="en">
    <script>
        $(document).ready(function () {
            $('[name = "brand_name"]').change(function (event) {
                var brand_name = $(this).val();
                $.get(
                    "action/ajax.php",
                    {brand_name: brand_name},
                    function (data) {
                        var opts = JSON.parse(data);
                        $.each(opts, function (i, d) {
                            $('[name="product_name"]').append('<option>', {
                                value: d.product_name,
                                text: d.product_name
                            });
                        });
                        //Enable the product_name select box
                        $('[name="product_name"]').prop('disabled', false);
                        //Refresh the product_name select box
                        $('[name="product_name"]').selectpicker('refresh');
                    }
                );
            });
        });
    </script>
</head>
<body>
<select required="required" name="brand_name">
    <option disabled selected>----SELECT----</option>
    <?php
    foreach ($brands as $row) {
        echo '<option value=' . $row['brand_name'] . '>' . $row['brand_name'] . '</option>';
    }
    ?>
</select>
<select required="required" name="product_name" disabled>
    <option disabled selected>SELECT</option>

</select>

</body>
</html>

【讨论】:

  • 它不工作......他向我展示了两个选项来选择,它们是第一个选择框中的“Z”。它甚至没有给我品牌......
  • 他告诉我 $ 没有定义
  • 第 8 行 $(document).ready(function () { 下方的 $
  • @AssadRajab - 我更新了我的答案以使用 JSON.parse 而不是 $.parseJSON
猜你喜欢
  • 1970-01-01
  • 2018-09-13
  • 2013-10-09
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
相关资源
最近更新 更多