ajax简介
Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
C#如何使用ajax
1.首先下载ajax.dll,一个百度一下都有下载的!自行查找。
2.把ajax.dll导入到工程。右键工程-->添加引用--->浏览,找到下载好的ajax.dll文件,点击确定,这时候在工程目录下多了一个bin文件夹,里面就有ajax.dll文件,这证明引入ajax.dll成功了。
3.设置配置文件web.config。
在Web.config文件下的 <system.web>节点里面添加以下代码即可:
1
2
3
|
< httpHandlers > < add verb = "POST,GET" path = "ajax/*.ashx" type = "Ajax.PageHandlerFactory, Ajax" /> </ httpHandlers > |
4.使用演示:
4.1 首先要对ajax进行注册。 在aspx.cs代码中的Page_Load方法里面对ajax进行注册,注册方式为Ajax.Utility.RegisterTypeForAjax(typeof(命名空间.类名)),假如没有命名空间可以直接写类名。代码如下:
1
2
3
4
5
6
7
|
public partial class ObjManage : System.Web.UI.Page { protected void Page_Load( object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax( typeof (ObjManage)); } } |
4.2 编写cs的方法,供javascript调用。cs方法前端必须要有[Ajax.AjaxMethod],然后方法必须是公有public、静态static。例如:
1
2
3
4
5
6
|
[Ajax.AjaxMethod] public static string getString( string str) { string strResult = "The string is " + str; return strResult; } |
4.3 javascript调用cs方法。调用的格式是:类名.方法名(参数),例如:
1
2
3
4
|
function alertString() { var str = ObjManage.getString( "myAjax" ).value; alert(str); } |
这样就完成了。这个是通过测试的,假如有什么问题,可留言。下面给出完成的源码,对于Web.config的代码就不给了,自己安装第3步设置配置文件web.config进行设置就OK了。cs代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ObjManage : System.Web.UI.Page { protected void Page_Load( object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax( typeof (ObjManage)); } [Ajax.AjaxMethod] public static string getString( string str) { string strResult = "The string is " + str; return strResult; } } |
aspx代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ObjManage.aspx.cs" Inherits="ObjManage" %> <!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 ></ title > < script type = "text/javascript" > function alertString() { var str = ObjManage.getString("myAjax").value; alert(str); } </ script > </ head > < body > < form id = "form1" runat = "server" > < div > < input type = "button" value = "获取信息" onclick = "alertString();" /> </ div > </ form > </ body > </ html > |
以上就是C# 如何使用ajax请求的详细内容,更多关于C# 使用ajax请求的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/sgxw/archive/2020/07/23/13365448.html