Asp. NET using Ajax

Source: Internet
Author: User

First, create a new HTML page, such as the registration page "Register.htm"
<!DOCTYPE HTML><HTML><Head>    <title>User Registration</title>    <MetaCharSet= "Utf-8" />    <styletype= "Text/css">. MSG{Color:Red;        }    </style></Head><Body>    <!--because it is an AJAX submission, the HTML form control does not have to be placed in the form and cannot be used to submit a button (type= "submit"), but with the normal button (type= "button") -User name:<inputtype= "text"name= "id"ID= "id" /><spanID= "Idmsg"class= "MSG"></span><BR/> <!--span is used to display error messages -Password:<inputtype= "Password"name= "pwd"ID= "pwd" /><spanID= "Pwdmsg"class= "MSG"></span><BR/>Name:<inputtype= "text"name= "Name"ID= "XM" /><spanID= "Namemsg"class= "MSG"></span><BR/>                    <inputID= "Btnreg"type= "button"value= "Register" />    <Scripttype= "Text/javascript"src= "Bootstrap/js/jquery.js">            </Script>    <Scriptsrc= "Reg.js"type= "Text/javascript"></Script>    </Body></HTML>
Second, a new JS file, such as: Reg.js
$(function() {    //define a function that clears the error message    functionclearmsg () {$ (". Msg"). HTML (""); }        //defines the function that gets the data for the form, noting that the JSON object is returned    functionFormData () {return{ID: $ ("#id"). Val (), PWD: $ ("#pwd"). Val (), Name: $ ("#xm"). Val ()}; }        //functions that define the registration function    functionReg () {varurl = "Register.ashx"; vardata =FormData ();        Clearmsg (); $.ajax ({type:' GET ',//automatically converts a JSON object to a query string appended to the URL such as: Http://localhost:49521/Register.ashx?id=a&pwd=b&name=cUrl:url, DataType:' JSON ',//requires the server to return a JSON type of data, such as: {"Success": TRUE, "message": "Registered successfully"}ContentType: ' Application/json ',//type of content encoding when sending information to the serverData:data,//data submitted to the server, directly using the JSON object's data, such as: {"id": "A", "pwd": "B", "Name": "C"} (if a JSON-formatted string is required, use json.stringify (data))Successfunction(ResponseData) {//If the response succeeds (that is, $)            if(Responsedata.success = =true) {//ResponseData is also in JSON format, such as: {"Success": TRUE, "message": "Registered successfully"}alert (responsedata.message); } Else {                varMsgs = Responsedata.msgs;//The Msgs object is an array, as follows:                //{"Success": false, "message": "Registration Failed", "msgs": [{"id": "pwdmsg", "message": "Password cannot be empty."},{"id": "namemsg", "Message": " The name cannot be empty. "}"}                     for(vari = 0; i < msgs.length; i++) {                        $(' # ' +msgs[i].id). html (msgs[i].message); }}}, error:function() {            //The function that is called when the request fails with a parameter that is required as a function type. The function has 3 parameters, the XMLHttpRequest object, the error message, and optionally the error object being captured. The Ajax event functions are as follows:            //function (XMLHttpRequest, textstatus, Errorthrown) {            //normally textstatus and Errorthrown only one of them contains information            //This ; Options parameters passed when calling this Ajax requestAlert (arguments[1]); }        });//Ajax    }        //define an initialization function    functionInit () {$ ("#btnReg"). Click (function() {reg ();    }); }        //Call initialization functioninit ();});
Third, the new general processing procedures, such as: Register.ashx
usingSystem;usingSystem.Collections;usingSystem.Data;usingSystem.Linq;usingsystem.web;usingSystem.Web.Services;usingSystem.Web.Services.Protocols;usingSystem.Xml.Linq;usingSystem.Collections.Generic;namespaceweblogin{/// <summary>    ///Summary description of $codebehindclassname $/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)]  Public classRegister1:ihttphandler { Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Application/json";//format the response content in JSON format            stringid = context. request["ID"]; stringPWD = context. request["pwd"]; stringName = Context. request["name"]; List<string> msglist =Newlist<string>(); if(String.IsNullOrEmpty (id)) {msglist.add ("{\ "id\": \ "idmsg\", \ "message\": \ "User name cannot be empty. \"}"); }            if(pwd==NULL|| pwd=="") {Msglist.add ("{\ "id\": \ "pwdmsg\", \ "message\": \ "password cannot be empty. \"}");//form: {"id": "pwdmsg", "message": "Password cannot be empty."}            }            if(name==NULL|| name=="") {Msglist.add ("{\ "id\": \ "namemsg\", \ "message\": \ "name cannot be empty. \"}"); }                        stringResponseText =""; if(Msglist.count = =0)            {                //calling background code to write to the databaseResponseText ="{\ "success\": True,\ "message\": \ "registration succeeded \"}"; }            Else            {                stringMsgsvalue ="";  for(inti =0; i < Msglist.count; i++) {Msgsvalue+ = Msglist[i] +",";//concatenate each string in the list, separated by "," but in the end there will be more ","} msgsvalue=msgsvalue.substring (0, Msgsvalue.length-1);//Remove the end of the ","Msgsvalue ="["+ Msgsvalue +"]";//enclosed in "[]", such as: [{"id": "pwdmsg", "message": "Password cannot be empty."},{"id": "namemsg", "message": "Name cannot be empty."}]ResponseText ="{\ "success\": False,\ "message\": \ "registration failed \", \ "Msgs\":"+ Msgsvalue +"}"; //The most metaphysical: {"Success": false, "message": "Registration Failed", "msgs": [{"id": "pwdmsg", "message": "Password cannot be empty."},{"id": "namemsg", " Message ":" The name cannot be empty. "}]}} context.        Response.Write (ResponseText); }         Public BOOLisreusable {Get            {                return false; }        }    }}
Iv. completion of the effect

Asp. NET using Ajax

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.