【发布时间】:2018-07-22 09:26:37
【问题描述】:
我有一个脚本,它允许从下拉选择中选择目录,然后在另一个下拉选择中显示其子目录。我正在尝试检查所选目录是否有子目录,如果有,则显示一条消息,指示是否有可用的子目录,即"no subdirs" 或"subdirs"。
问题是警报消息显示的是从目录下拉列表中选择的最后一个元素,而不是当前目录选择。
例如,如果当前选择的是目录 2,而之前的选择是目录 1,则为目录 1 显示 document.getElementById("subdir").options.length;,而不是目录 2。我不确定问题出在哪里,所以请帮忙将不胜感激,谢谢。
<script type='text/javascript'>
$(function() {
$("#dirs").on('change', function() {
var Dir = $(this).val();
//Make an ajax call
$("#subdir").html('<option>Loading...</option>');
$.get("ajax.php?Dirs=" + encodeURIComponent(Dir), function(data) {
$("#subdir").html(data);
});
});
});
</script>
<script>
function myFunction() {
var y = document.getElementById("subdir").options.length;
alert(y);
if (y <= 1) {
alert('no subdirs');
} else if (y > 1) {
alert('subdirs');
}
}
</script>
<select id="dirs" name="Dirs" onChange="myFunction()">
<option value="" selected="selected" disabled="yes">Select Directory</option>
<?php
$dirs = glob("/*", GLOB_ONLYDIR);
foreach($dirs as $val){
echo '<option value="'.$val.'">'.basename($val)."</option>\n";
}
?>
</select>
<select name="subdir" id="subdir" required>
<option value="Select Sub Directory" selected="selected" disabled="yes">Select Sub Directory</value>
</select>
还有ajax.php:
<?php
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Check for passed dir exist
$folder = $_GET['Dirs'];
if(!file_exists($folder)) {
exit('Folder Not Found');
}
$out = '';
$files = array_filter(glob($folder.'/*'), 'is_dir');
echo '<option value="Select Sub Directory" selected="selected" disabled = "yes">Select Sub Directory</value>';
foreach($files as $val){
$out .= '<option value="'.$val.'">'.basename($val)."</option>\n";
}
//Output the file options
exit($out);
}
?>
【问题讨论】:
-
</value>????? -
因为您在 Ajax 调用返回之前正在阅读它...
标签: javascript php html ajax