asp.net WebService实现跨域js调用功能实现

1、Web.Config中增加如下红色标记部分配置:

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <!--提供Ajax调用开始 -->
    <webServices>
        <protocols>
            <add name="HttpGet" />
            <add name="HttpPost" />
        </protocols>
    </webServices>
    <!--提供Ajax调用结束-->

  </system.web>


2、增加一个Tools类,如下代码:

    public class Tools
    {
          public static void WriteResult(string callback, string result)
          {
               HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.UTF8;
               HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
               HttpContext.Current.Response.Write(callback + "(" + result + ")");
               HttpContext.Current.Response.End();
          }
    }


3、WebService文件增加头属性


    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    [System.Web.Script.Services.ScriptService]
    [SoapDocumentService(RoutingStyle = SoapServiceRoutingStyle.RequestElement)]

    public class getData : System.Web.Services.WebService
    {

        #region 1、获取设备信息

        [WebMethod]
        public void GetAllDeviceData()
        {
            string sql = @"select devid,jfid,devname from JfDevice";
            DataTable dtTable = AosySql.ExecuteforDataSet(sql).Tables[0]; //获取数据库数据的方法,使用的数据库访问类,根据自身情况调整
            StringBuilder sb = new StringBuilder();
            if (dtTable.Rows.Count > 0)
            {
                foreach (DataRowView drv in dtTable.DefaultView)
                {
                    sb.Append("{\"DevId\":\"" + drv["devid"].ToString() + "\",");
                    sb.Append("\"DevName\":\"" + drv["devname"].ToString() + "\",");
                    sb.Append("\"JfId\":\"" + drv["jfid"].ToString() + "\"},");
                }
            }
            string result = "[" + sb.ToString().TrimEnd(',') + "]";
            Tools.WriteResult(HttpContext.Current.Request["jsoncallback"], result);
        }

   }


4、将WebService发布到IIS后,在其他系统中的html页面中调用,如下代码所示:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="JS/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            getValueFromWebService();
        });

        //查询webservice
        function webservice(url, callback) {
            $.ajax({
                type: 'get',
                url: url,
                dataType: 'jsonp',
                jsonp: 'jsoncallback',
                success: function (result) {
                    callback(result);
                }
            });
        };


        function getValueFromWebService() {
            webservice('http://192.168.33.158/XXXX/WebService/getData.asmx/GetAllDeviceData',
                function (obj) {
                    var data = obj;
                    //成功
                    $.each(data, function (key, item) {
                        // 添加项目内容到ul列表中
                        $('<li>', { text: formatItem(item) }).appendTo($('#room'));
                    });
                });
        }

        function formatItem(item) {
            return item.DevId + ' /  ' + item.DevName + ' / ' + item.JfId;
        }
    </script>
</head>
<body>
    <ul id="room">
    </ul>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值