jQuery跨域调用WebService

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
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明, 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利
posted @ 2012-10-21 22:59  zengql  阅读(8675)  评论(4编辑  收藏  举报