![](/img/trans.png)
[英]how to retrieve data from database based on the value of two drop down list using ajax?
[英]How to retrieve data from database using AJAX based on a select tag?
假設我們有兩個選擇標簽
<select id='combobox_1'>
<option value='1'>Description of fist record</option>
<option value='2'>Description of second record</option>
</select>
<select id='combobox_2'></select>
和數據庫上的兩個表
表格1
combox_1_db_id PK
combox_1_db_description
table_2
combox_2_db_id PK
combox_1_db_id FK
combox_2_db_description
現在,我想使用在combobox_1中選擇的選項的值向PHP發送一個AJAX請求,以根據combobox_1_id用來自數據庫combobox_2的記錄來填充。
JS
$('#combobox_1').on('change', function() {
var option_value = $('#combobox_1').find('option:selected').val();
$.ajax({
url: '/get_records',
method: 'GET',
dataType: 'JSON',
success: function(data) {
$(data).each(function() {
var option = $('<option />');
option.attr('value',
this.combox_2_id).text(this.combox_2_description);
$('#combobox_2').append(option);
});
},
error: function() {
console.log('Error on loading records');
}
});
});
的PHP
$this->router->get_request('/get_records', function() {
$records= $this->soap_server->getRecords(array(
'combox1Id' => $_GET['combox_1_id']
));
echo json_encode($records->return);
});
但是我找不到將ID發送給PHP的方法,因此我可以基於該ID獲取記錄並將它們加載到combobox_2中,我們將不勝感激。
您可以將option_value發送到ajax中,只需將其作為數據包括在內即可。
$('#combobox_1').on('change', function() {
// get the id of the selected option
var id = $(this).children(":selected").attr("id");
$.ajax({
url: '/get_records',
method: 'GET',
dataType: 'JSON',
data: {combox_1_id: id}, // send the id in the request
success: function(data) {
$(data).each(function() {
var option = $('<option />');
option.attr('value',
this.combox_2_id).text(this.combox_2_description);
$('#combobox_2').append(option);
});
},
error: function() {
console.log('Error on loading records');
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.