下面的后台的代码:目的的查询数据库中的所有省的列表,然后转化为json传到前端页面
@Controller
public class DistrictController {
@Resource
private ProvinceService provinceServiceImp;
@Resource
private CityService cityServiceImp;
@Resource
private TourSpotService tourSpotServiceImp;
/**
* 获取所有省信息
* @param response
* @return
* @throws IOException
*/
@RequestMapping("/getAllProvince")
public String getAllProvince(HttpServletResponse response) throws IOException{
response.setContentType("text/html;charset=utf-8");//设置响应的编码格式,不然会出现中文乱码现象
PrintWriter out = response.getWriter();
//get
List<Province> provincelist = provinceServiceImp.findAllProvince();
JSONArray jsonArray = JSONArray.fromObject(provincelist);
out.write(jsonArray.toString());
out.flush();
out.close();
return null;
}
以下是前端jquery内容:
$.get("/visualization-tour/getAllProvince", function(result) {
var json = eval("("+result+")"); // 解析
var tt = "<option selected class='proInfo' value=1>~请选择省~</option>";
$.each(json, function(index) {
// 循环获取数据
var proId = json[index].proId;
var proName = json[index].proName;
tt += "<option value="+proId+">"+proName+"</option>" ;
});
$("#province").html(tt);
});
下面就是实际效果了:
注意事项,SpringMVC的控制器会是你的一些静态资源(js、html、css)不能加载,需要修改SpringMVC的配置文件,添加以下内容:
<!-- 静态资源访问 -->
<mvc:resources location="/img/" mapping="/img/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/page/" mapping="/page/**" />
其中location 是指你的静态资源的路径
就到这里了,祝你顺利运行