Javascript AJAX访问C#webservice

步骤:
1.创建要访问的webservice。
创建一个名为AjaxWebService的webservice,然后增加两个方法LoginPost 和 LoginGet,分别用来测试POST方式和GET方式的AJAX请求。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace AjaxWebService
{
    /// <summary>
    /// AdminWebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    //**如果希望webservice可以通过ajax方式访问,需要这行**
    [System.Web.Script.Services.ScriptService]   
    public class AdminWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        /// <summary>
        /// Ajax通过POST方式访问该方法
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [WebMethod]         
        //[ScriptMethod(UseHttpGet=true,ResponseFormat=ResponseFormat.Json)]            
        public int LoginPost(string username, string password)
        {
            if (username.Equals("lisi") && password.Equals("123456"))
                return 0 ;
            return 1;
        }

        /// <summary>
        /// Ajax通过GET方式访问该方法
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [WebMethod]
        //如果AJAX通过GET方式访问该方法,必须设置 UseHttpGet属性的值为 true,否则报500错误。
        [ScriptMethod(UseHttpGet = true)]
        public bool LoginGet(string username, string password)
        {
            if (username.Equals("lisi") && password.Equals("123456"))
                return true;
            return false;
        }
    }
}

webservice创建完毕。

2.创建网页访问webservice。
(1) 创建GET方式的AJAX测试页面,代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="loginGet.aspx.cs" Inherits="AjaxTest.loginGet" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>测试页面</title>
    <script type="text/ecmascript">
        var xmlHttp = new XMLHttpRequest();
        window.onload = function () {
            document.getElementById('btn_login').onclick = function () {

                var username = document.getElementById('username').value;
                var password = document.getElementById('password').value;
                if (xmlHttp == null || xmlHttp == undefined)
                    alert('xmlHttp对象未创建');
                xmlHttp.open('GET', '/Ajax_WebService/AdminWebService.asmx/LoginGet?username=' + username + '&password=' + password);
                xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
                xmlHttp.onreadystatechange = ajaxCallBack;
                xmlHttp.send(null);             
            };

            document.getElementById('btn_reset').onclick = function () {
                document.getElementById('username').value = '';
                document.getElementById('password').value = '';
            };

            function ajaxCallBack() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        var responseFormat = xmlHttp.getResponseHeader('Content-Type');
                        alert(responseFormat);
                        var result = xmlHttp.responseText;
                        alert(result);
                    }
                }
            }
        }
    </script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        用户名:<input type="text" name="username" id="username"/><br />
        密  码:<input type="text" name="password" id="password"/><br />
        <input type="button" id="btn_login" value="登录" />     <input type="button" id="btn_reset" value="重置"/>
        <a href="http://localhost/Ajax_WebService/AdminWebService.asmx/Login?username=yanshuqiang&password=123456a?">测试连接</a>
    </div>
    </form>
</body>
</html>

GET方式访问webservice,请求参数需要添加到URL当中。

(2) 创建POST方式的AJAX测试页面,代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="loginPost.aspx.cs" Inherits="AjaxTest.loginPost" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>测试页面</title>
    <script type="text/ecmascript">
        var xmlHttp = new XMLHttpRequest();
        window.onload = function () {
            document.getElementById('btn_login').onclick = function () {

                var username = document.getElementById('username').value;
                var password = document.getElementById('password').value;
                if (xmlHttp == null || xmlHttp == undefined)
                    alert('xmlHttp对象未创建');               
                var requestJson = JSON.parse('{"username":"' + username + '","password":"' + password + '"}');
                xmlHttp.open('POST', '/Ajax_WebService/AdminWebService.asmx/LoginPost');
                xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
                xmlHttp.onreadystatechange = ajaxCallBack;   
                xmlHttp.send('{"username":"' + username + '","password":"' + password + '"}');
            };

            document.getElementById('btn_reset').onclick = function () {
                document.getElementById('username').value = '';
                document.getElementById('password').value = '';
            };

            function ajaxCallBack() {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        var responseFormat = xmlHttp.getResponseHeader('Content-Type');
                        alert(responseFormat);
                        var result = JSON.parse(xmlHttp.responseText);
                        alert(result.d);
                    }
                }
            }
        }
    </script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        用户名:<input type="text" name="username" id="username"/><br />
        密  码:<input type="text" name="password" id="password"/><br />
        <input type="button" id="btn_login" value="登录" />     <input type="button" id="btn_reset" value="重置"/>
        <a href="http://localhost/Ajax_WebService/AdminWebService.asmx/Login?username=yanshuqiang&password=123456a?">测试连接</a>
    </div>
    </form>
</body>
</html>

使用POST方式访问webservice,如果需要传递参数,可以通过json方式传递,返回数据可以为json或者xml格式。
注意:如果需要返回结果返回json格式数据,需要在xmlHttp对象open之后,send之前通过setRequestHeader(‘Content-Type’,’application/json;charset=utf-8’)设置。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值