Ajax (. NET) Notes for beginners

Source: Internet
Author: User

The following is a rough record of the. NET video from instructor Yang zhongke (Chuanzhi podcast) and the Ajax chapter in the video publishing system of instructor Niu Yu,Beginner's understanding is limited, so the notes may be incorrect..

I. Use the original JS Code to implement Ajax(No Ajax framework is needed)

1,New ajaxtext.html

-Click "button1" to obtain the server time and display it in the text1 text box.

<! 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"> 

 2,Add JS Code to implement Ajax

-Note: if Javascript or jquery is written in a separate JS file, the URL of the ashx page is relative to the HTML or ASPX page, rather than the JS page.

<SCRIPT type = "text/JavaScript"> function btnclick () {var XMLHTTP = new activexobject ("Microsoft. XMLHTTP "); // create an XMLHTTP object, which is equivalent to WebClient (note that this is a method in Microsoft IE and is not supported in other browsers) if (! XMLHTTP) {alert ("An error occurred while creating the XMLHTTP object! "); Return false;} // The getdate to be sent to the server. the ashx page sends a POST request and passes the parameter ID, & TS = new date (). gettime () prevents pages from caching XMLHTTP. open ("Post", "getdate. ashx? Id = "+ encodeuri (" China ") +" & TS = "+ new date (). gettime (), false); // XMLHTTP default (also recommended) is not a synchronous request, that is, the open method does not get the server response data as the downloadstring of WebClient, is asynchronous, so you need to listen to the onreadystatechange event XMLHTTP. onreadystatechange = function () {If (XMLHTTP. readystate = 4) {// The Server Request completes if (XMLHTTP. status = 200) {// If the status code is 200, the request is successful document. getelementbyid ("text1 "). value = XMLHTTP. responsetext ;//★The responsetext attribute is the text returned by the server} else {alert ("error returned by the Ajax server! ") ;}} XMLHTTP. Send (); // The request is sent.} </SCRIPT>

3,Create a general handler page getdate. ashx

Public void processrequest (httpcontext context) {context. response. contenttype = "text/plain"; string id = context. request ["ID"]; context. response. write (datetime. now. tostring () + "-- the parameter id =" + id) transmitted from the page; // get the server time,★Return data through context. response. Write}

Note: ashx uses context. response. Write () to return data.

 Ii. Use jquery to implement Ajax (jquery is generally used to implement Ajax, which is more convenient)

Introduce the jquery. js file and change the JS Code in step 1 to jquery code.

Function btnclick () {$. post ("getdate. ashx ", {" ID ":" China "}, function (data, status) {If (status =" success ") {// The second parameter status indicates the status code returned by the server. Success indicates that success is returned $ ("# text1 "). val (data); // The first parameter data is the content returned by the server} else {// alert ("ajax error! ");}});}

Jquery provides methods to simplify Ajax usage. $. Ajax () is an Ajax access function provided by jquery. Generally, $. Ajax () is not directly called,

$. Post ()Is the encapsulation of the Ajax query submitted by the $. Ajax () Post method, and the $. Get () method to the $. Ajax () Get Method to the Ajax query. The post method is recommended because there is no cache problem in the post method.

To execute a function when an error occurs, use $. Ajax.

$. Post (URL, [data], [callback], [type]):234th the parameter is optional

URL: It is the address for sending the request, as shown in the preceding getdate. ashx (note that the ashx page path here is relative to the page path, rather than the JS file path)

Data:The key/value parameter to be sent is a dictionary array, for example, {"ID": idtext, "name": nametext}. You can also write the URL as "getdate. ashx? Id = "+ idtext +" & name = "+ nametext format. If the parameter is omitted, the POST method automatically encodes the passed Chinese parameters;

(★Note: If you use $. get () must solve the cache problem. You can add the parameter "T": new date (). gettime (); encoding must also be considered. If the input parameter value is Chinese, garbled characters are generated in the database. Therefore, you must perform secondary transcoding, for example, "name ": encodeuri (nametext), and then decode the context value in ashx. server. urldecode (context. request ["name"], so we recommend that you use $. post ())

Calback:Callback function when sending successfully, as shown in the preceding function (data, status) {}, In the callback functionData (omitted)For the data returned by the server,Status (omitted)Return status code for the serverStatus = "success"Success

3. The data returned in the preceding method is a single string and can be transmitted as an Array Using JSON.

1,Create a new jsontest.html file and add jquery code to the HTML file.

<SCRIPT type = "text/JavaScript"> $ (function () {$. post ("jsontest. ashx ", function (data, status) {// alert (data); // The dictionary array row string {" name ":" Tom "," Age ": 30} var person = $. parsejson (data); // reverse sequence, directly obtain a dictionary array alert (person. name); // equivalent to person ["name"]}) ;}); </SCRIPT>

2,Create jsontest. ashx

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. services; using system. web. script. serialization; // introduce the namespace Ajax {[WebService (namespace = "http://tempuri.org/")] [webservicebinding (conformsto = wsiprofiles. basicprofile1_1)] public class jsontest: ihttphandler {public void processrequest (httpcontext context) {context. response. contenttype =" Text/plain "; // javascriptserializer provides serialization and deserialization functions for afax-enabled applications. Javascriptserializer JSS = new javascriptserializer (); // serialize (): when being rewritten in a derived class, a dictionary array of name/value pairs is generated. String JSON = JSS. serialize (new person () {name = "Tom", age = 30}); context. response. write (JSON); // returns a dictionary array string: {"name": "Tom", "Age ": 30 }} public bool isreusable {get {return false ;}} public class person {public string name {Get; Set ;}public int age {Get; Set ;}}}
Related Article

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.