在一個select框中,option往往是寫好的,這樣難以適應數據庫中項目的動態變化,因此需要將option中的項目與數據庫數據進行綁定,本項目使用Spring Boot進行開發,下面演示綁定方法。
首先在前端定義一個基本select框,在這里把第一項寫好了,並顯示為select框的默認項。
<select id="selectshijuan" class="selectSJ" style="width: 200px"> <option value="0">--請選擇試卷--</option> </select>
接着在mapper中寫數據庫查詢語句,在service中寫查詢方法
ShitifenxiMapper
@Component public interface ShitifenxiMapper { @Select("SELECT DISTINCT shijuanming FROM fenshu WHERE shitileixing = '填空題' ORDER BY shijuanming") public List<String> getShijuanming(); }
ShitifenxiService:
@Service public class ShitifenxiService { @Autowired private ShitifenxiMapper shitifenxiMapper; public List<String> getShijuanleixing(){ return shitifenxiMapper.getShijuanming(); } }
下一步在controller中接受試卷名並傳給JS
@Controller public class ShitifenxiController { @Autowired ShitifenxiService shitifenxiService; //填充試卷名 @PostMapping(value = "/shijuanming") @ResponseBody public List<String> shijuanleixing(){ List<String> sjm=shitifenxiService.getShijuanleixing(); return sjm; } }
最后,在JS中接受傳入的試卷名並填充到select框的option中:
function fillShijuanming(){ var optionJson=[]; $.ajax({ type: "post", url: "/shijuanming", data: {}, async:false, success : function(data){ optionJson=data; var selectObj=document.getElementById("selectshijuan"); for(var i=0;i<optionJson.length;i++){ selectObj.add(new Option(optionJson[i],optionJson[i])); } } }); }
至此,就可以在前端頁面的select框中看到從數據庫中獲取的數據了。