Spring Boot页面中select选项绑定数据库数据

  在一个select框中,option往往是写好的,这样难以适应数据库中项目的动态变化,因此需要将option中的项目与数据库数据进行绑定,本项目使用Spring Boot进行开发,下面演示绑定方法。

  首先在前端定义一个基本select框,在这里把第一项写好了,并显示为select框的默认项。

<select id="selectshijuan" class="selectSJ" style=" 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框中看到从数据库中获取的数据了。

原文地址:https://www.cnblogs.com/liesun/p/7416969.html