一、前端代码:
function initDeptSelect() {var datas = {"plant":$('#plantSelect').val()}; //获取某个组件的值,以json格式形式存放var jsonVal = JSON.stringify(datas);//将值转化为json对象,必须要做 $.ajax({type: 'post', //请求方式url: 'Upload.aspx/initDeptSelect', //请求地址data: jsonVal, //发送的数据,这里是json对象dataType: 'json', //数据类型contentType: 'application/json;charset=utf-8',async: true, //开启异步请求success: function (data) { //请求成功,后台处理结束后的函数执行var $select = $("#deptSelect");var jsonObject = $.parseJSON(data.d); //将返回的数据解释为一个数组,data是后台函数的返回值,返回到前端的时候,会多变成{d:"[xxx,xx,xx]"}$.each(jsonObject, function (key, value) {var $option = $('<option></option>');$option.attr('value', jsonObject[key]);$option.text(jsonObject[key]);$select.append($option);});$('#deptSelect').selectpicker('refresh');$('#deptSelect').selectpicker('render');},error: function (XMLHttpRequest, textStatus, errorThrown) {alert("Failed to get Dept Informations.");alert(XMLHttpRequest.responseText);alert(XMLHttpRequest.status);alert(XMLHttpRequest.readyState);alert(textStatus); // parser error; }});}
二、后台代码
这里用WinForm,跟MVC稍微有点区别:WinForm是在方法上面用[WebMethod]声明,而MVC是用[HttpPost]声明
[WebMethod]public static string initDeptSelect(string plant)//后台获取json:plant的值,参数个数要与传递的一致,否则,ajax请求失败 {List<string> deptList = new List<string>();deptList.Add("hello");deptList.Add("world");//使用JsonConvert.SerializeObject(List list)最为方便;或者使用字符串拼接的形式,如拼接成{xxx:xxx,xx:xx}的字符串,然后返回return JsonConvert.SerializeObject(deptList);}