[英]how to Populate datas into select element by Ajax call using js at first
我有一個包含兩個選擇選項的html
頁面,它是通過onclick()
函數中的ajax調用從Servlet獲取值的。 但是我第一次沒有將數據填充到選擇選項中。 下次單擊時,僅填充值。 我知道第一次它只是將選項添加到select元素。 第一次單擊時如何填充數據。 這是我的代碼。
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form>
<table>
<tr>
<th>Name</th>
<td><input type="text" name="fName"></td>
</tr>
<tr>
<th>Age</th>
<td><input type="text" name="age"></td>
</tr>
<tr>
<th>Country</th>
<td>
<select name="country" id="country" onclick="loadCountry()">
<option selected="selected">-- Select --</option>
</select>
</td>
</tr>
<tr>
<th>State</th>
<td>
<select name="state">
<option value="">-- Select --</option>
</select>
</td>
</tr>
</table>
</form>
<script type="text/javascript">
var status = true;
function loadCountry()
{
var xhttp;
var cArray;
var cArrayJs;
if(status)
{
if(window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function()
{
var selectCountry = document.getElementById("country");
if(this.readyState == 4 && this.status == 200)
{
cArray = this.responseText;
cArrayJs = JSON.parse(cArray);
for(x in cArrayJs)
{
selectCountry.add(new Option(cArrayJs[x]));
}
status = false;
}
}
}
xhttp.open("GET","servlet1",false);
xhttp.send();
}
</script>
</body>
</html>
根據我的觀點,這是在頁面加載時加載選擇selectlist
的最佳做法,但是如果您想在單擊下拉菜單上執行相同的操作,則可以按照以下代碼片段進行操作,其中只有一個Ajax調用會第二次執行不打ajax電話。
我也想讓你看一下這個演示
var loaded = false; $(".Staus").text(loaded); $("#country").on("click", function() { $(".Staus").text(loaded); if (loaded) return; var selectCountry = document.getElementById("country"); selectCountry.add(new Option("Hello1")); selectCountry.add(new Option("Hello2")); selectCountry.add(new Option("Hello3")); loaded = true; $(".Staus").text(loaded); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="country" id="country"> </select> DropDown Loaded : <Label class="Staus"></Label>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.