Javascript呼叫.axd文档
axd文档与ashx文档有相似的功能。此博文中,Insus.NET演示如何在Javascript呼叫到axd文档。能呼叫到axd文档,当然也可以呼叫到ashx的,不过此次axd是主角。
在你的专案的App_Code中,创建一个类别,记得要实作IHttpHandler接口。
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for InsusClass
/// </summary>
namespace Insus.NET
{
public class InsusClass : IHttpHandler
{
public InsusClass()
{
//
// TODO: Add constructor logic here
//
}
public bool IsReusable
{
get { throw new NotImplementedException(); }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/Plain";
string parm = context.Request.Params["v"];
context.Response.Write("Hello, " + parm);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for InsusClass
/// </summary>
namespace Insus.NET
{
public class InsusClass : IHttpHandler
{
public InsusClass()
{
//
// TODO: Add constructor logic here
//
}
public bool IsReusable
{
get { throw new NotImplementedException(); }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/Plain";
string parm = context.Request.Params["v"];
context.Response.Write("Hello, " + parm);
}
}
}
然后,在web.config注册axd文档:
为了做一个演示,我们可以在.aspx放置一个TextBox和一个Button。这样用户可以在文本框中输入文字,点击铵钮可以呼叫到它。
View Code
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:Button ID="ButtonCall" runat="server" Text="Call"
OnClientClick="callAxd();" />
<asp:Button ID="ButtonCall" runat="server" Text="Call"
OnClientClick="callAxd();" />
在铵钮中使用了OnClientClick="callAxd();", 是客户端执行,可以直接Ctrl + C,Ctrl + V帖于head 即可。
View Code
function callAxd() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
var url = "i.axd?v=" + document.getElementById('<%=TextBoxName.ClientID%>').value;
xhr.open("GET", url, true);
xhr.send();
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
var url = "i.axd?v=" + document.getElementById('<%=TextBoxName.ClientID%>').value;
xhr.open("GET", url, true);
xhr.send();
}
OK,我们运行一下: