本节介绍的内容是在上一篇文章的基础上增加的,
http://www.cnblogs.com/alvinyue/archive/2011/05/17/2048783.html
上一篇介绍了如何从前台异步获取json数据(有很多不足之处,望广大网友指正,谢谢!),这一次介绍另一个方法 $.get(),它的原型是:jQuery.get( url, [ data ], [ success(data, textStatus, jqXHR) ], [ dataType ] ),就不用解释了!如下:
About.cshtml
$(function () {
//get the schools
$.get("/Home/GetSchools", function (data) {
$(data).each(function () {
var o = document.createElement("option");
o.value =this['Id'];
o.text =this['Name'];
$("#sltSchool")[0].options.add(o);
});
});
// Get the departments depend on the school
$("#sltSchool").change(function () {
// initialization the select
$("#sltDepartment").empty();
var _o = document.createElement("option");
_o.value ="-1";
_o.text ="select...";
$("#sltDepartment")[0].options.add(_o);
$.get("/Home/GetDepartments", { schoolId: $("#sltSchool").val() }, function (data) {
$(data).each(function () {
var o = document.createElement("option");
o.value =this['Id'];
o.text =this['Name'];
$("#sltDepartment")[0].options.add(o);
});
});
});
});
//get the schools
$.get("/Home/GetSchools", function (data) {
$(data).each(function () {
var o = document.createElement("option");
o.value =this['Id'];
o.text =this['Name'];
$("#sltSchool")[0].options.add(o);
});
});
// Get the departments depend on the school
$("#sltSchool").change(function () {
// initialization the select
$("#sltDepartment").empty();
var _o = document.createElement("option");
_o.value ="-1";
_o.text ="select...";
$("#sltDepartment")[0].options.add(_o);
$.get("/Home/GetDepartments", { schoolId: $("#sltSchool").val() }, function (data) {
$(data).each(function () {
var o = document.createElement("option");
o.value =this['Id'];
o.text =this['Name'];
$("#sltDepartment")[0].options.add(o);
});
});
});
});
所调用的后台方法如下:
Controller
public JsonResult GetSchools()
{
returnthis.Json(TestModels.GetAllSchools (),JsonRequestBehavior.AllowGet);
}
public JsonResult GetDepartments(int schoolId)
{
returnthis.Json(TestModels.GetDepartmentBySchoolId(schoolId),JsonRequestBehavior.AllowGet);
}
{
returnthis.Json(TestModels.GetAllSchools (),JsonRequestBehavior.AllowGet);
}
public JsonResult GetDepartments(int schoolId)
{
returnthis.Json(TestModels.GetDepartmentBySchoolId(schoolId),JsonRequestBehavior.AllowGet);
}
都是很基础的东西,欢迎提出宝贵意见,谢谢!