使用jquery Ajax異步刷新 下拉框
阿新 • • 發佈:2018-04-01
pre htm 引入 log mar script items ppa pty
一個下拉框
<label>產品類型:</label> <select id="protype" name="protype" onchange="getNameList()"> <option value="">--請選擇--</option> </select>
響應上一個下拉框的結果
的另一個下拉框
<label>產品名稱:</label> <select id="proname" name="proname"> <option value="">--請選擇--</option> </select>
引入jquery包
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
異步刷新代碼
function getNameList() { var id = $(‘#protype‘).val(); if (id === "") { $(‘#proname‘).html(‘‘); var options = ‘‘; options+= ‘<option value="">--請選擇--</option>‘; $(‘#proname‘).append(options); return; } var obj = { id: id }; AjaxCall(‘/Home/GetProList‘, JSON.stringify(obj), ‘POST‘).done(function (response) { if (response.length > 0) { $(‘#proname‘).html(‘‘); var options = ‘‘; options += ‘<option value="">--請選擇--</option>‘; for (var i = 0; i < response.length; i++) { options += ‘<option value="‘ + response[i].Value + ‘">‘ + response[i].Text + ‘</option>‘; } $(‘#proname‘).append(options); } }).fail(function (error) { $(‘#proname‘).html(‘‘); var options = ‘‘; options += ‘<option value="">--請選擇--</option>‘; $(‘#proname‘).append(options); }); } function AjaxCall(url, data, type) { return $.ajax({ url: url, type: type ? type : ‘GET‘, data: data, contentType: ‘application/json‘ });
後臺響應代碼
/// <summary> /// 用於處理異步刷新下拉框 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpPost] public ActionResult GetProList(string id) { List<SelectListItem> elems = null; if (string.IsNullOrEmpty(id)) elems = null; else { string filePath = Server.MapPath("/App_Data/SimpleData.xml"); string filter = string.Format("/DD/DItems[@DValue=‘{0}‘]", id); elems = GetListByXpath(filePath, filter); } return Json(elems, JsonRequestBehavior.AllowGet); }
總結 :
重點在於使用ajax異步post成功之後,處理服務器返回來的數據
使用jquery Ajax異步刷新 下拉框