I'm trying to get data via AJAX when the select is changed, which is why I used .trigger()
.
但是,它似乎不起作用。我可以顺利地从数据库中获取数据,然后通过 AJAX 将其传递给 item-type。
这里是。
HTML
<!doctype>
<html>
<head>
<title>Coupon Protoype</title>
<link rel="stylesheet" type="text/css" href="css/coupon.css">
</head>
<body>
<div class="body-wrap">
<section class="wrap-form">
<label for="item-types">Item Types</label><select id="item-types"></select>
<label for="item-list">Items</label><select id="item-list"></select>
<input type="text" placeholder="Check Code" id="input-code"/>
<input type="button" id="button-check" value="Check"/>
</section>
<section class="output-wrap">
<label>Coupon Code:</label> <label id="coupon-code"></label>
</section>
</div>
</body>
<script type="text/javascript" src="javascript/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="javascript/coupon.js"></script>
</html>
Javascript
$(document).ready(function(){
function get_items_type(){
$.ajax({
type:'POST',
url:'coupon-functions.php',
dataType:'json',
data:{'switch-num':'1'},
success:function(data){
if(data.error){
alert(data.error);
}
var html = '';
$.each(data, function(i, item) {
html += "<option value="+data[i].item_type_id+">"+data[i].item_type+"</option>";
});
$('#item-types').append(html);
}
})
}
/这一行就是我所说的 $("#item-types").on("change",function(){
var item_type_id = $(this).val();
$.ajax({
type:'POST',
url:'coupon-functions.php',
dataType:'json',
data:{'switch-num':'2','item_type_id':item_type_id},
success:function(data){
if(data.error){
alert(data.error);
}
var items = '';
$('#item-list').html("");
$.each(data, function(i, item) {
items += "<option value="+data[i].item_id+">"+data[i].item_name+"</option>";
});
$('#item-list').append(items);
}
})
});
$("#item-types").trigger("change");
get_items_type();
});
PHP
<?php
include_once('db_connect.php');
$switch_number = $_POST["switch-num"];
switch ($switch_number) {
case '1':
get_item_list();
break;
case '2':
get_item();
break;
}
function get_item_list(){
$get_items = "SELECT * FROM item_type_info";
$query_get_items = mysql_query($get_items);
$data = array();
if(!$query_get_items){
$data['error'] = die(mysql_error());
}
while($row = mysql_fetch_array($query_get_items)){
$data[] = array( 'item_type_id' => $row['item_type_id'],
'item_type' => $row['item_type'] );
}
echo json_encode($data);
}
function get_item(){
$item_type_id = $_POST['item_type_id'];
$get_items = "SELECT * FROM item_info a
LEFT JOIN item_type_info b
ON(a.item_type_id = b.item_type_id)
WHERE a.item_type_id = '$item_type_id' ";
$query_get_item = mysql_query($get_items);
$item = array();
if(!$query_get_item){
$item['error']=die(mysql_error());
}
while($row = mysql_fetch_array($query_get_item)){
$item[] = array( 'item_id' => $row['item_id'],
'item_name' => $row['item_name']);
}
echo json_encode($item);
}
?>
我.on()
用作.live()
. 我只需要在加载页面时使其工作,触发器将在选择列表中进行更改。