浅谈Ajax请求C#后台的几种方式

Ajax技术的出现可以说是B/S架构的一个里程碑,直接奠定了B/S模式的软件在市场的地位。Ajax的一些背景我就不在这里多说了。这里主要介绍一下怎么通过Javascript和JQuery使用Ajax技术请求后台。

1.后台设计之ashx
ashx:一般处理程序,是.NET众多的web组件之一,类似于Java中的Servlet。在.Net中需要实现IHttpHandler接口。这个接口有一个IsReusable成员和一个待实现的方法ProcessRequest(HttpContextctx) 。程序在processRequest方法中处理接受到的Http请求。成员IsReusable指定此IhttpHnadler的实例是否可以被用来处理多个请求,主要应用于并发访问时该成员会起到作用。

定义一个ashxTest.ashx,下面是创建该文件后工具自动生成的,工具的操作这里不做过多的赘述,不明白的读者可以去看一些基础教程,推荐去慕课网和我要自学网这2个网站,基础教程还是比较详细的。

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

namespace WebTest1
{
    /// <summary>
    /// ashxTest 的摘要说明
    /// </summary>
    public class ashxTest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

我们把ProcessRequest这个方法做些改动,先看下请求方式,Web调试没有控制台,可以选择输出到文本文件或者断点调试就可以看到请求方式,这里使用断点调试

public void ProcessRequest(HttpContext context)
{
    string method = context.Request.HttpMethod;
    context.Response.ContentType = "text/plain";
    context.Response.Write("Hello World");
}

启动网站后直接在浏览器中输入网址,就可以命中断点,这时候就可以查看这个context.Request.HttpMethod的值,这种形式都是GET请求,POST请求需要借助工具如Postman,或者使用AJAX
http://localhost:61556/ashxTest.ashx
在这里插入图片描述
现在使用AJAX请求并传入一些参数,创建一个WebForm1.aspx,前台设计如下:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <input type="button" 'ajaxTest("GET")' value="AJAX测试之GET请求"/>
       <input type="button" 'ajaxTest("POST")' value="AJAX测试之POST请求"/>
    </div>
    </form>
    <script type="text/javascript">
        function ajaxTest(method)
        {
            var request;
            if(window.XMLHttpRequest)
            {
                request = new XMLHttpRequest();
            }
            else
            {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (method === "GET")
            {

                request.open("GET", "ashxTest.ashx?param1=张三&param2=男");
                request.send();
                request.onreadystatechange = function () {
                    if (request.readyState === 4 && request.status === 200) {
                        alert(request.responseText);
                    }
                }
            }
            else
            {
                request.open("POST", "ashxTest.ashx");
                request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                request.send("param1=小芳&param2=女");
                request.onreadystatechange = function () {
                    if (request.readyState === 4 && request.status === 200) {
                        alert(request.responseText);
                    }
                }
            }
        }
    </script>
</body>
</html>

后台做一些修改,获取这些参数并返回给前台,注意分GET和POST两种情况去获取

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    string httpMethod = context.Request.HttpMethod;
    string param1,param2;
    if(httpMethod == "GET")
    {
        //获取GET请求参数
        param1 = context.Request.QueryString["param1"];
        param2 = context.Request.QueryString["param2"];
        context.Response.Write("GET请求:"+param1 + "   " + param2);
    }
    else if(httpMethod=="POST")
    {
        param1 = context.Request.Form["param1"];
        param2 = context.Request.Form["param2"];
        context.Response.Write("POST请求:" + param1 + "   " + param2);
    }
}

测试:
在这里插入图片描述
在这里插入图片描述

很多东西都是固定的写法,是语言开发者提供的使用文档,读者根据实际业务变换自己的写法。如果真的想要去追溯原理,那需要花费相当多的时间。

2.后台设计之WebMethod
前端做些调整,使用JQuery进行ajax请求
注意点:
(1)要引入JQuery脚本
(2)WebMethod只支持POST请求
(3)请求格式用JSON,响应格式也用JSON
WebForm2.aspx设计如下:

<form id="form1" runat="server">
    <div>
        <asp:Button runat="server" Text="ajax测试WebMethod请求" OnClientClick="ajaxWebMethod()"/>
        <input type="button" "ajaxWebMethod()" value="ajax测试WebMethod请求"/>
        <span id="id"></span>
    </div>
</form>
<script type="text/javascript">
    function ajaxWebMethod()
    {
    	var d = {
            "user":
                {
                    "name": "张三",
                    "age":25
                }
        }
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            url: "http://localhost:61556/WebForm1.aspx/Method1",
           data: JSON.stringify(d),
            dataType: "json",
            success: function (data) {
                $("#id").text(data.d);
            },
            error:function(err)
            {
                $("#id").text("发生错误");
            }
        });
        return false;
    }
</script>

后台在WebForm1.aspx.cs页面下加入如下代码,注意参数的设置必须和ajax传的json数据保持一致才能正确接受。这里接受后直接再序列化该对象返回,不做任何其他处理,JsonConvert是Newtonsoft.Json.dll工具里的一个工具类,SerializeObject方法可用于序列化给定对象。

[WebMethod(Description ="WebMethod测试")]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string Method1(User user)
{
	return JsonConvert.SerializeObject(user);
}

User类的结构和ajax给定的结构保持一致,下面给出User

public class User
{
    private string name;
    private int age;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    public int Age
    {
        get { return age; }
        set { age = value; }
    }
}

测试
在这里插入图片描述
在这里插入图片描述
这样一个Ajax请求WebMethod的流程走完了,有些需要注意的地方要说下:
有时候ajax不一定非要传对象,如果只是传几个json字符串,那么webmethod的参数也要严格保持一致,如data:"{“name”:“张三”,“age”:25}",此时后台的WebMethod的参数应该为public static string Method1(string name,int age)。还有就是被注解为WebMethod的方法必须为静态方法。

3.后台设计之WebService
WebForm3.aspx页面设计

<form id="form1" runat="server">
    <div>
        <input type="button" "ajaxWebMethod()" value="ajax测试WebService请求"/>
        <span id="id"></span>
    </div>
</form>
<script type="text/javascript">
        function ajaxWebMethod()
        {
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                url: "http://localhost:61556/WebService1.asmx/HelloWorld",
                data: "{\"name\":\"小华\",\"age\":25}",
                dataType: "json",
                success: function (data) {
                    $("#id").text(data.d);
                },
                error:function(err)
                {
                    $("#id").text("发生错误");
                }
            });
            return false;
        }
</script>

WebService1.asmx.cs后台设计,WebService中的方法必须为非静态的,参数设计与WebMethod一致

/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
	[WebMethod]
    public string HelloWorld(string name,int age)
    {
        return name+"   "+age;
    }
}

测试:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值