<select class='form-control' id='make' placeholder='Make:'>
<select class='form-control' id='model' placeholder='Model:'>
<select class='form-control' id='version' placeholder='Version:'>
我有一个函数,可以根据单击的下拉列表的值来更新未单击的“其他”下拉列表中的值-但对于每个下拉列表,我都会重复此函数3次
$('#model').change(function(){
let selectedModel = $(this).val();
$.ajax({
url: 'PHP/dropdown.PHP',type: 'POST',data: {model: selectedModel},success:function(data)
{ $('#make').html('');
$('#version').html('');
let makeJSON = JSON.parse(data)[0];
let versionJSON = JSON.parse(data)[2];
for (let i = 0; i < makeJSON.length; i++) {
if (makeJSON[i].mMake!= '' && makeJSON[i].mMake!= null) {
$('#make').html($('#make').html() + '<option value="' + makeJSON[i].mMake + '">' + makeJSON[i].mMake + '</option>');
}
}
for (let i = 0; i < versionJSON.length; i++) {
if (versionJSON[i].mVersion != '' && versionJSON[i].mVersion != null) {
$('#version').html($('#version').html() + '<option value="' + versionJSON[i].mVersion + '">' + versionJSON[i].mVersion + '</option>');
}
}
}
});
});
PHP看起来像这样:
$model = $_REQUEST['model'];
$sqlupdateModel = "SELECT DISTINCT mMake,mVersion FROM Cars WHERE mModel = '$model';
$stmtModel = sqlsrv_query( $conn,$sqlupdateModel);
if( $stmtModel === false)
{
die( print_r( sqlsrv_errors(),true));
}
$updateModel = [];
while( $row = sqlsrv_fetch_array( $stmtModel,sqlSRV_FETCH_ASSOC)){
$updateModel[] = $row;
}
echo json_encode(array($updateMake,$updateModel,$updateVersion));
…这一切都很好,
基本上,我正在寻找一种更简单的解决方案来重用该函数(包括JS和PHP),而不是重写3次!
根据我的尝试,
$('#make,#model,#version').change(function(){
let columnValue = $(this).val();
.......
data: {model: columnValue},success:function(data)
{$(this).html(''); //this doesn't work obvIoUsly!
在这之后我被斯诺克
最佳答案
这应该适用于JS端,您将必须检查映射功能以获得响应
$('#make,#version').change(function(ev){
let selected = $(this).val();
let id = ev.target.id;
let data = {};
data[id] = selected;
$.ajax({
url: 'PHP/dropdown.PHP',data: data,success:function(data)
{
let options = ['make','model','version']
const response = {
make: JSON.parse(data[0].map(make => make.mMake)),model: JSON.parse(data[1].map(make => make.mModel)),version: JSON.parse(data[2].map(make => make.mVersion))
}
options.filter(option => option !== id).forEach(option => setDropdown(option,response[option]));
}
});
});
function setDropdown(id,data) {
const id = `#${id}`
$(id).html('');
for (let i = 0; i < data.length; i++) {
if (data[i] != '' && data[i] != null) {
$(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
}
}
}