C# 使用jquery 中Ajax异步调用。详解。教程详解

参考网上的例子  比较容易懂的,适合我这样的初学者。

用了两种方式,一个是简单的Ajax异步程序,另一个是一般处理程序

一、这个是简单的Ajax异步程序。直接在后台处理请求。

在demo1.aspx页面操作

 $(function () {  //这个是页面初始化
            $("#btn1").click(function () {
                var txtparam1 = $("#txtParam1").val();
                var txtparam2 = $("#txtParam2").val();

                $.ajax({
                    url: "demo1.aspx/AjaxMethod",//发送到本页面后台AjaxMethod方法
                    type: "POST",
                    dataType: "json",
                    async: true,//async翻译为异步的,false表示同步,会等待执行完成,true为异步
                    contentType: "application/json; charset=utf-8",//不可少。不设置这个,json也是返不回来的

                    data: "{param1:'" + txtparam1 + "',param2:'" + txtparam2 + "'}",
                    success: function (data) {
                        $("#result").html(data.d);// d?
                    },
                    error: function () {
                        alert("请求出错处理");
                    }
                });

            });
        });

将数据传到后台.cs代码(demo1.aspx.cs)F7,在demo1.aspx.cs中AjaxMethod()方法中做数据处理

namespace AjaxDemo
{
    public partial class demo1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        //type方式必须是post,方法必须是静态的,方法声明要加上特性 
         //[System.Web.Services.WebMethod()],传递的参数个数也应该和方法的参数相同。
        [System.Web.Services.WebMethod()]
        public static string AjaxMethod(string param1, string param2)
        {
            return "参数1为:"+param1+",参数2为:"+param2;
        }
    }
}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

二、这个是自定义处理后台数据的文件。

      ajax发送请求。将参数传到一般处理程序(demo1.ashx)中。

 $(function () {
            $("#btn2").click(function () {
                var params = {};//参数数组
                params.action = "GetAjaxValue";
                params.param1 = $("#txtParam1").val();
                params.param2 = $("#txtParam2").val();

                $.ajax({
                    url: "AjaxHandler.ashx",//指向一般处理程序。
                    data: params,
                    type: "POST",
                    async: true,
                    //contentType: "application/json; charset=utf-8",//加了这句,程序会无法把参数params 传到一般处理程序中。
                    dataType: "json",
                    beforeSend: function () {
                       //发送请求前执行
                    },
                    success: function (msg) {
                        if (msg.OperateResult == "success") {
                            if (msg.ResponseData.length > 0) {
                                $("#result").html(msg.ResponseData);
                            }
                        }
                    },
                    error: function (e) {
                        alert("请求出错处理");
                    },
                    complete: function () {
                    }
                });
            });
        });

        2.新建一个一般处理程序AjaxHandler.ashx文件。在这里就行后台数据处理。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;//必须

namespace AjaxDemo
{
    /// <summary>
    /// AjaxHandler 的摘要说明
    /// </summary>
    public class AjaxHandler : IHttpHandler
    {
        private JavaScriptSerializer json = new JavaScriptSerializer();
        private string operateSuccess = "success";
        private string operateFailed = "false";
        public void ProcessRequest(HttpContext context)
        {
            string jsonObject = string.Empty;
            string action = context.Request["action"];
            //context.Response.ContentType = "text/plain";//服务端需要返回一段普通文本给客户端 
            context.Response.ContentType = "application/json;charset=utf-8";//服务端需要返回一段json串给客户端 

            if (action == "GetAjaxValue")
            {
                try
                {
                    string param1 = context.Request["param1"];
                    string param2 = context.Request["param2"];
                    string result = "第一个参数:" + param1 + "第一个参数:" + param2;

                    jsonObject = json.Serialize(new { OperateResult = operateSuccess, ResponseData = result });
                }
                catch (Exception e)
                {
                    jsonObject = json.Serialize(new { OperateResult = operateFailed, ResponseData = e.Message });
                }
            }
            context.Response.Write(jsonObject);
        }

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

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在ASP.NET Web项目,可以使用Ajax进行异步调用方法。下面是一个C#的代码示例: 1. 首先,在你的Web项目添加一个Web服务(.asmx文件)或者Web API控制器(.cs文件),定义一个需要被异步调用的方法。 ```csharp // Web服务(.asmx文件)示例 [WebMethod] public string GetServerTime() { return DateTime.Now.ToString(); } // Web API控制器(.cs文件)示例 [HttpGet] public string GetServerTime() { return DateTime.Now.ToString(); } ``` 2. 在前端页面引入jQuery库和JavaScript代码,使用Ajax进行异步调用。 ```html <!-- 引入jQuery库 --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- JavaScript代码 --> <script> $(document).ready(function () { // 使用Ajax异步调用方法 $.ajax({ type: "GET", // 请求类型(GET、POST等) url: "YourWebService.asmx/GetServerTime", // Web服务的url或Web API控制器的路由 contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { // 异步调用成功后的处理 var serverTime = response.d; // 获取返回的数据 console.log(serverTime); }, error: function (xhr, status, error) { // 异步调用失败后的处理 console.log(error); } }); }); </script> ``` 请注意,上述示例的"YourWebService.asmx/GetServerTime"或者"YourApiController/GetServerTime"需要根据你的实际情况进行替换。另外,如果你的Ajax调用返回的是JSON格式的数据,可以在success回调函数进行进一步的处理,并根据需要更新页面内容。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值