[英]Populate html dropdown list using Ajax function call during page load
我有一個下拉列表,需要使用json文件中的內容填充。 我有一個php文件,可以解析此json文件並回顯所需的輸出。
這是我的json,
<?php
$filecontents = file_get_contents('users.txt');
$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($filecontents, TRUE)),RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(!is_array($val) && $key == "templatename"){
echo '<option>'.$val.'</option>';
}
}
?>
這是我的html頁面,
<script>
window.onload = function() {
loadTest();
};
function loadTest()
{
var xmlhttp=new XMLHttpRequest();
document.getElementById("testdropdown").innerHTML=xmlhttp.responseText;
xmlhttp.open("get","2test.php",true);
xmlhttp.send();
}
</script>
<select name="test dropdown" id="testdropdown"></select>
我進行的ajax查詢似乎無效。
這是我的php文件的輸出,
<option>1-1</option><option>1-2</option>
頁面加載時,在<script>
標記內添加以下內容之一以調用loadTest():
如果您使用jQuery:
$(document).ready(function() {
loadTest();
});
除此以外:
window.onload = function() {
loadTest();
};
原來我錯過了幾行代碼,
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("testdropdown").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("get","2test.php",true);
xmlhttp.send();
這似乎可以解決它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.