我有一個表單,用戶可以從100個問題列表中選擇一個特定問題。一旦更新<Select id="problem">
字段,下面的MySQL查詢將通過AJAX啓動。AJAX - 選擇具有多個值的字段填充
if(isset($_POST['action']) && ($_POST['action']=='problem_lookup')) {
if(isset($_POST['problem'])) {
// Start MySQLi connection
include 'connect_db.php';
$db = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
// display error if connection cannot be established
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']'); }
// run query
$sql = "SELECT Category, Department_Responsible, Alert, Experience FROM qci_problems_index_new WHERE Issue='".$_POST['problem']."' GROUP BY Issue";
$result = $db->query($sql) or die(mysqli_error($db));
// return data as array
$array = mysqli_fetch_array($result);
echo json_encode($array);
}
}
查詢將返回幾個值這是每一個表單填寫到個人<select>
領域中,唯一的例外是<select id="alert-dept" multiple>
字段,它可以有多個值,這就是問題的所在。
現在,除alert-dept
之外的所有字段都按預期填充了一個特定值,但如果查詢返回2個或更多值,則該字段保持空白。我想我通過AJAX填充字段時必須使用foreach()
等效的JavaScript,但由於我不知道如何做到這一點而丟失了。
這裏的代碼,我用它來填充查詢結果中的表單字段。
<script type="text/javascript" language="javascript">
$(function() {
$('#problem').change(function() { // on change in field "problem"
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: '../../plugins/MySQL/ajax_action.php',
data: { action: 'problem_lookup' , problem: $("#problem").val() },
dataType: 'json', // encode with JSON
success: function (data)
{
var data0 = data[0]; // assign row[0] result to variable = Problem Category
var data1 = data[1]; // assign row[1] result to variable = Dept Responsible
var data2 = data[2]; // assign row[2] result to variable = Alert
var data3 = data[3]; // assign row[3] result to variable = Experience
$('#problem_category').val(data0); // insert result into field
$('#department').val(data1); // insert result into field
$('#alert_dept').val(data2);
$('#experience').val(data3);
$('#problem_category').trigger('change'); // refresh select field via trigger('change') to show the result
$('#department').trigger('change');
$('#alert_dept').trigger('change');
$('#experience').trigger('change');
},
});
});
});
所以'data [2]'是一個類似於[['value1','value2','value3']'的數組? –
對不起,是的,忘了提及它的逗號分隔值。例如。 'Person 1','Person 2','Person 3'' – Armitage2k
我想我誤解了你的問題 - alert-dept是否已經擁有所有必要的選項,並且data [2]將擁有一組值選擇? –