1. 程式人生 > >java jsp 頁面下拉框 ajax非同步載入數庫資料

java jsp 頁面下拉框 ajax非同步載入數庫資料

全面詳細的新手下拉框資料顯示。web專案中難免用到下拉框非同步載入資料的情況。這裡分享一個。使用的是jquery的ajax非同步載入後臺資料。後臺使用java語言。

1,先看效果,下拉框如下:


2.獲取值:


3.html頁面程式碼:

/js/jquery-1.8.2.min.js 這個檔案是需要引入的,為了用ajax。

$(function () {
    setDa();
});
function setDa(){
    var url="http://"+window.location.host+"/monitor-web/web/selectBox.do?server_type="+server_type;
$.ajax({ url: url, type:"post", dataType: "json", data : { "c_type" : "c", "t_type":"b" }, success:function (data){ var selectOption = ""; selectOption += "<option></option>"; $.each(data, function(n, value) { // alert(n+" --"+JSON.stringify(value));
selectOption+="<option value="+value.s_value+">"+value.s_label+"</option>" }); $('#selectbox').html(selectOption); } }); }; function getDa(){ // alert($('#selectbox')); var d=document.getElementById("selectbox").value; alert(d); };

<select id="selectbox" style="width: 200px"
> </select> <input type="button" value="取值" style="width: 200px;height: 30px" onclick="getDa()">

4.java後臺:這裡把值value和顯示的標籤label放入json中實現。至於資料庫嘛,查出資料往obj裡面放就好了

@RequestMapping("/selectBox")
public String selectBox(HttpServletRequest request, HttpServletResponse response) throws Exception {

    System.out.println("組裝下拉框資料");
JSONObject js1;
JSONArray all=new JSONArray();
    for (int i=0;i<5;i++){
        js1=new JSONObject();
js1.put("s_value","pro"+i);
js1.put("s_label","顯示"+i);
all.put(js1);
}
    response.setContentType("text/json;" + "charset=UTF-8");
response.getWriter().write(all.toString());
    return null;
}