Explain how to implement the most basic AJAX framework

Source: Internet
Author: User
Ajax|ajax Framework |

Environment: Window Xp SP2 +. Net framwwork 2.0.50727.

asp.net 2.0 self-brought client callback

ASP.net 2.0 has been released. 2.0 has many new features, and the client callback is one of them. The client callback allows us to invoke the server-side method without a postback, which is consistent with the functionality provided by Ajax, but not as flexible as Ajax, where Ajax can customize the calling method, with 2.0 of its own callback capabilities. The System.Web.UI.IcallbackEventHandler interface must be implemented to use the client callback feature.

This interface contains two methods:

Fixed call this method when client callback

public void RaiseCallbackEvent (String eventargument)

This method is called after the raisecallbackevent has been executed. The return value of this method is sent back to the client

public string GetCallbackResult ()


Example one:

. CS:

String cbreference = Page.ClientScript.GetCallbackEventReference (

This is, "Arg", "receiveserverdata", "context");

String Callbackscript;

Callbackscript = "function CallServer (ARG, context)" + "{" + Cbreference + "};";

Page.ClientScript.RegisterClientScriptBlock (

This. GetType (), "CallServer", Callbackscript, True);

Javascript:

Introduction to Ajax

Ajax is not a new technology, but an organic combination of some existing technologies, mainly including: XmlHttp, reflect. An AJAX framework basically includes a custom HttpHandler, a section of JavaScript code.

Ajax operating mechanism

Before we use XMLHTTP to achieve no Refresh page, is to use XMLHTTP to request a hidden page, using (asp/asp.net) from the HttpHandler, and in Ajax, we are asking for a hidden page, The difference is that the HttpHandler of this page is implemented by ourselves.
1. First we implement an HTTP handler (HttpHandler) to respond to the client's request:

Implementing a custom HttpHandler requires implementing the IHttpHandler interface.

The interface contains a property and a method:

BOOL Ihttphandler.isreusable

void Ihttphandler.processrequest (HttpContext context)

Example:

BOOL Ihttphandler.isreusable

{

get {return true;}

}

void Ihttphandler.processrequest (HttpContext context)

{

Context. Response.Clear (); Gets the method to invoke

String methodname = Context. Request.querystring["Me"];

Gets the assembly information.

Czhenq.AJAX.Class1.Dencode is a custom string encoding method

String assemblyname = Czhenq.AJAX.Class1.Dencode (context. Request.querystring["as"]);

Gets the parameters of the method

String Arguments = context. request.querystring["AR"]; Start Calling method

Type type = Type.GetType (AssemblyName);

MethodInfo method = Type. GetMethod (MethodName,

BindingFlags.NonPublic | BindingFlags.Public | bindingflags.static | BindingFlags.Instance);

if (method!= null)

{

Parameter uses the "," delimited

string[] args = Arguments.split (",". ToCharArray ());

Parameterinfo[] Paras = method. GetParameters ();

object[] argument = new Object[paras. Length];

for (int i = 0; i < argument. Length; i++)

{

if (i < args. Length) {

The conversion must be made because the parameters passed by XMLHTTP are all string types.

Only the parameters are converted to Int32, and there is no other consideration.

Argument[i] = Convert.ToInt32 (Args[i]);

}

}

Object value = method. Invoke (Activator.CreateInstance (type, true), argument);

if (value!= null) context. Response.Write (value. ToString ());

else context. Response.Write ("error");

}

End of process

Context. Response.End ();

}

2. Client JavaScript code:

function Callmethod (Assemblyname,methodname,argus)

{

var args = "";

for (Var i=0;i<>

args + = Argus[i] + ",";

if (args.length>0) args = Args.substr (0,args.length-1);

var xmlhttp = new ActiveXObject (' microsoft.xmlhttp ');

url = "ajax/ajax.czhenq?as=" + AssemblyName + "&me=" + methodname + "&ar=" + args;

Xmlhttp.open ("POST", Url,false);

Xmlhttp.send ();

alert (Xmlhttp.responsetext);

}



3. A simple AJAX framework has been implemented. Now write a piece of code to test.
Use your own Ajax

1. Create a new website and apply the HttpHandler you just wrote. and register your HttpHandler in the web.config of the website, stating that those requests will be processed using the handler you write. The following description: All requests ending with "CZQ" will be processed using "czhenq.httphandlerfactory".



< p="" verb="POST,GET" path="*.czq">

Type= "czhenq.httphandlerfactory, Czhenq.ajax"/>



2. Add a Web page, copy just the script to the page, and add a method you want to call.

private string Add (int i, int j)

{

return TextBox1.Text;

}



3. Place a HiddenField control on the page named AssemblyName. and add the following code to the Page_Load:

String assemblyname = Czhenq.AJAX.Class1.Encode (

typeof (_default). AssemblyQualifiedName);

Assemblyname.value = AssemblyName;



4. Add the following script to the page:

var assemblyname = document.getElementById ("AssemblyName");

var argus = new Array ();

Argus.push ("100");

Argus.push ("200");

Callmethod (AssemblyName, "Add", Argus);



Summary Ajax is not a new technology, it's just an organic combination of some existing technologies, and we can simply interpret Ajax as: Ajax is the encapsulation of calling XMLHTTP on JavaScript, which changes the way code is written.

attached Encode and Dencode implementation:

public static string Encode (string value)

{

byte[] bytes = ASCIIEncoding.ASCII.GetBytes (value);

Return convert.tobase64string (bytes);

}

public static string Dencode (string value)

{

byte[] bytes = convert.frombase64string (value);

Return ASCIIEncoding.ASCII.GetString (bytes);

}

<

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.