我對JS很新,所以我確信有一個簡單的方法可以做到這一點。將AJAX響應的第一個元素設置爲下拉列表中的選定值
我試圖從AJAX響應的第一個元素創建一個下拉菜單。響應看起來是這樣的:
[0: "14Z18Oct2017", 1: "13Z18Oct2017", 2: "12Z18Oct2017", ... 14: "00Z18Oct2017"]
我居住沒有問題的下拉菜單,但在頁面加載,我想選擇下拉作爲默認的第一個元素(這將被用來動態顯示目錄中的圖像)。
我使用HAniS,一個HTML圖像動畫web應用程序在AJAX響應的目錄中拼接圖像。 HAniS需要一個指向圖像的路徑,我已經把它放在get_config()函數的底部。
這是我到目前爲止有:
config.js
function get_config() {
var basepath = "http://site/times/";
$.ajax({
url: '../times.php', //a php script echoing an array of directory contents
datatype: 'json',
success: function(dirs) {
$.each(dirs, function(index, date) {
$('#times').append($('<option></option>').val(date).html(date));
}
}
})
// Here's part of the config JSON that HAniS requires
var hancon = {
// image_only_base should be:
// "http://site/times/14Z18Oct2017/" -> basepath + first element of response
image_only_base: basepath + $('#times').val()
// this is where I'm lost
}
};
的index.html
<body onload="get_config()">
<div id="testing">
<select id="times">
<!-- the options here are created via AJAX -->
<!-- need the first value listed to be selected by default -->
<option value="14Z18Oct2017">14Z18Oct2017</option>
<option value="13Z18Oct2017">14Z18Oct2017</option>
<...>
<option value="00Z18Oct2017">14Z18Oct2017</option>
</select>
</div>
</body>
我覺得get_config的最後一行()函數是問題。
我用$('#times').val()
刺了一下,但沒有返回值。
我也試過:
$('#times').val(1),
$('#times').val(0),
$("#times option:selected").val()
和其他幾個人。
如何引用下拉列表的第一個元素來動態創建路徑? (響應的內容將會不斷變化 - 連續的python腳本正在向路徑添加更多目錄)
感謝所有的提前。
哪裏'dates'從哪裏來,你的成功函數的參數被稱爲'dirs'。無論如何,假設你有'成功:函數(日期){'那麼第一個將是'日期[0]',所以在你填充下拉後,你可以將它的值設置爲日期[0]的值。 – James
@詹姆斯對此抱歉,在我的轉錄中搞砸了。現在修復它。 – nat5142