【发布时间】: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