因此,当页面加载时,我尝试同时填充三个选择框。框的数据来自数组。因此,一个框用于$cpuArr,一个框用于$motherboardsArr,一个框用于$videocardArr。
$cpuArr = file_get_contents('data/cpu.json');
$motherboardsArr = file_get_contents('data/motherboard.json');
$videocardArr = file_get_contents('data/video-card.json');
if(isset($_POST['request']) == 1){
echo $cpuArr;// Sending response
}jQuery
$(document).ready(function(){
//Ajax request
$.ajax({
url: 'logic.php',
type: 'post',
data: {request: 1},
dataType: 'json',
success: function fetchItems(response){
for( var i = 0; i< response.length; i++){
$('#cpu').append("<option value='"+response[i]['ID']+"'>"+response[i]['Name']+"</option>");
}
}
});
}); <select id='cpu'>
<option value="0">-Select CPU-</option>
</select>
<select id='motherboard'>
<option value="">-Select motherboard-</option>
</select>
<select id='video-card'>
<option value="">-Select Video Card-</option>
</select>它只工作一个,我不知道如何做三个盒子,而不归还代码,我将感激如果有人可以帮助。:)
发布于 2021-05-09 14:34:48
您可以在associative array内部传递所有数据,然后使用json_encode即:
if(isset($_POST['request']) == 1){
$data = array("cpuArr"=>$cpuArr,
"motherboardsArr"=>$motherboardsArr,
"videocardArr"=>$videocardArr);
echo json_encode($data);
}然后,在ajax的成功函数中,您可以像下面这样访问它们:
success: function fetchItems(response){
var cpu = response.cpuArr;
var mb = response.motherboardsArr;
var vdio = response.videocardArr;
for( var i = 0; i< cpu.length; i++){
$('#cpu').append("<option value='"+cpu[i]['ID']+"'>"+cpu[i]['Name']+"</option>");
}
//same for others ...
}发布于 2021-05-09 15:12:29
您可以在一个请求中完成所有这些,只需使用$.getJSON()发出一个GET请求。
PHP
function getFileAsArray($type){
$path = "data/".$type.".json";
return json_decode(file_get_contents($path), true);
}
$types = ['cpu','motherboard','video-card'];
foreach($types as $type){
$output[$type] = getFileAsArray($type);
}
echo json_encode($output);JQuery:
$.getJSON('logic.php').then(data => {
$.each(data, (key, arr)=>{
const options = arr.map(o => new Option(o.Name, o.ID));
// keys in php matching ids in html
$('select#' + key).append(options);
});
});https://stackoverflow.com/questions/67458752
复制相似问题