html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>jquery跨域調用WebService(getJson)</title> <style type="text/css"> * { font: 12px 宋體; margin: 0px; padding: 0px; } body { padding: 5px; } #container .search { height: 20px; } #container .result { margin-top: 5px; } #txtUserName { float: left; } #btnSearch { float: left; margin: 0px 0px 0px 5px; width: 78px; height: 16px; text-align: center; line-height: 16px; background-color: #eee; border: solid 1px #BABABA; cursor: pointer; } #btnSearch:hover { width: 76px; height: 14px; line-height: 14px; background-color: #fff; border-width: 2px; } .mark { color: Blue; } </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> //用戶信息(全局) var userData = { //WebServices地址(GetUserList=方法名稱,?jsoncallback=?--必須包含) requestUrl: "http://localhost:54855/PersonalServices.asmx/GetUserList?jsoncallback=?", //方法參數(用戶名可用","分隔開來查詢多個用戶信息) requestParams: { userName: null }, //回調函數 requestCallBack: function (json) { if (json.ResponseStatus == 1) {//成功獲取數據 var addRow = function (key, value) { return "<span>" + key + ":</span><span class=\"mark\">" + value + "</span><br/>"; } userData.resultData = json.ResponseData; var resultHtml = ""; $(userData.resultData).each(function () { resultHtml += addRow("姓名", this.Name); resultHtml += addRow("年齡", this.Age); resultHtml += addRow("性別", this.Sex); resultHtml += addRow("備注", this.Remark); resultHtml += "<br/>"; }); $(".result").html(resultHtml); } else $(".result").html(json.ResponseDetails); //無數據或者后台處理失敗! }, //查詢得到的數據 resultData: null }; $(function () { //綁定文本框的鍵盤事件 $("#txtUserName").keyup(function () { if ($.trim($(this).val()) == "") { $(".result").html("請輸入查詢用戶名!"); } else { userData.requestParams.userName = $(this).val(); $(".result").html(""); } }); //綁定查詢按鈕單機事件 $("#btnSearch").click(function () { if (userData.requestParams.userName) { $.getJSON(userData.requestUrl, userData.requestParams, userData.requestCallBack); } }); }); </script> </head> <body> <form id="form1" runat="server"> <div id="container"> <div class="search"> <input type="text" id="txtUserName" /><div id="btnSearch"> 查 詢</div> </div> <div class="result"> </div> </div> </form> </body> </html>
WebServices.cs
using System; using System.Collections.Generic; using System.Web; using System.Web.Services; #region 命名空間 using Newtonsoft.Json; #endregion namespace WebService { /// <summary> /// PersonalServices 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class PersonalServices : System.Web.Services.WebService { #region 獲取用戶信息 [WebMethod] public void GetUserList(string userName) { List<Personal> m_PersonalList = new List<Personal>(); string[] strArr = userName.Split(','); foreach (string item in strArr) { Personal m_Personal = GetUserByName(item); if (m_Personal != null) { m_PersonalList.Add(m_Personal); } } ResponseResult responseResult = new ResponseResult(); if (m_PersonalList.Count == 0) { responseResult.ResponseDetails = "沒有查到該用戶!"; responseResult.ResponseStatus = 0; } else { responseResult.ResponseData = m_PersonalList; responseResult.ResponseDetails = "查詢用戶信息成功!"; responseResult.ResponseStatus = 1; } string jsoncallback = HttpContext.Current.Request["jsoncallback"]; //返回數據的方式 // 其中將泛型集合使用了Json庫(第三方序列json數據的dll)轉變成json數據字符串 string result = jsoncallback + "(" + JsonConvert.SerializeObject(responseResult, Formatting.Indented) + ")"; HttpContext.Current.Response.Write(result); HttpContext.Current.Response.End(); } #endregion #region 模擬數據庫處理結果 /// <summary> /// 根據用戶名查詢用戶 /// </summary> /// <param name="userName">用戶名</param> /// <returns></returns> Personal GetUserByName(string userName) { List<Personal> m_PersonalList = new List<Personal>(); m_PersonalList.Add(new Personal() { Id = "01", Name = "liger_zql", Sex = "男", Age = 21, Remark = "你猜......" }); m_PersonalList.Add(new Personal() { Id = "02", Name = "漠然", Sex = "女", Age = 22, Remark = "猜不透......" }); foreach (Personal m_Personal in m_PersonalList) { if (m_Personal.Name == userName) { return m_Personal; } } return null; } #endregion #region json數據序列化所需類 /// <summary> /// 處理信息類 /// ResponseData--輸出處理數據 /// ResponseDetails--處理詳細信息 /// ResponseStatus--處理狀態 /// -1=失敗,0=沒有獲取數據,1=處理成功! /// </summary> class ResponseResult { public List<Personal> ResponseData { get; set; } public string ResponseDetails { get; set; } public int ResponseStatus { get; set; } } /// <summary> /// 用戶信息類 /// </summary> class Personal { public string Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } public string Remark { get; set; } } #endregion } }
WebService項目配置文件
<system.web> <!--提供Web服務訪問方式--> <webServices> <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="Documentation"/> </protocols> </webServices> </system.web>
由於使用jquery.getJson的方式調用Web服務后,傳遞中文時會造成中文亂碼問題:
所以在配置文件中應配置如下內容:
<system.web> <!-- 設定傳參亂碼問題 --> <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8"/> </system.web>
調用截圖如下:
最后附上源碼:JqCrossDomain.zip
作者:曾慶雷
出處:http://www.cnblogs.com/zengqinglei
本頁版權歸作者和博客園所有,歡迎轉載,但未經作者同意必須保留此段聲明, 且在文章頁面明顯位置給出原文鏈接,否則保留追究法律責任的權利