Very simple Ajax request instance with source code, ajax instance source code

Source: Internet
Author: User

Very simple Ajax request instance with source code, ajax instance source code

Ajax is not a new programming language, but a technology used to create better, faster, and more interactive Web applications. With Ajax, you can use the XMLHttpRequest object of JavaScript to directly communicate with the server. You can exchange data with the Web server without reloading the page. In this example, we will demonstrate how the webpage communicates with the web server when a user inputs data into a standard HTML form.

<! 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> <meta http-equiv =" Content-Type "content =" text/html; charset = UTF-8 "/> <title> simple Ajax request </title> <script type =" text/javascript "> var xmlHttp; // create the XMLHttpRequest object function createXMLHttpRequest () {if (window. activeXObject) {xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");} else if (window. XMLHttpRequest) {xmlHttp = new XMLHttpRequest () ;}// integrates the url parameter function createQueryString () {var Name = document. getElementById ("txtName "). value; var sex = document. getElementById ("txtSex "). value; var birthday = document. getElementById ("txtBirthday "). value; var queryString = "Name =" + encodeURIComponent (name) + "& Sex =" + encodeURIComponent (sex) + "& Birthday =" + encodeURIComponent (birthday ); return queryString;} // pass the function doRequestUsingGET () {createXMLHttpRequest (); var querySt according to the Get Method Ring = "AjaxServer. ashx? "; QueryString = queryString + createQueryString () +" & timeStamp = "+ new Date (). getTime (); xmlHttp. onreadystatechange = handleStateChange; xmlHttp. open ("GET", queryString, true); xmlHttp. send (null);} // pass the function doRequestUsingPOST () {createXMLHttpRequest (); var url = "AjaxServer. ashx? TimeStamp = "+ new Date (). getTime (); var queryString = createQueryString (); xmlHttp. open ("POST", url, true); xmlHttp. onreadystatechange = handleStateChange; xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded;"); xmlHttp. send (queryString);} // callback function handleStateChange () {if (xmlHttp. readyState = 4) {if (xmlHttp. status = 200) {parseResults () ;}}// process the server response Content function parseResults () {var responseDiv = document. getElementById ("serverResponse"); if (responseDiv. hasChildNodes () {responseDiv. removeChild (responseDiv. childNodes [0]);} var responseText = document. createTextNode (xmlHttp. responseText); responseDiv. appendChild (responseText) ;}</script> 

The functions of each JS function are described in detail below.
CreateXMLHttpRequest ()Used to create an XMLHttpRequest object.
Because IE implements XMLHttpRequest as an ActiveX object, other browsers (FF/Safari/Opera) implement it as a local JavaScript Object. Due to these differences, JavaScript code must contain the relevant logic.
CreateQueryString ()It is used to sort parameters and format the parameters to be passed in Ajax requests.
If URL encoding is required for passing Chinese or non-ASCII characters, this example uses the JS encodeURIComponent () function to encode the parameter URL.
DoRequestUsingGET ()Send an http get request to the server and pass parameters.
The open () method of the XMLHttpRequest object specifies the request to be sent. The open () method has three parameters: a string indicating the method used (usually GET or POST), a string indicating the URL of the target resource, and a Boolean value, the request is asynchronous.
When a GET request is sent, the passed parameter is written to the url parameter of the open method. The parameter of the send method is null.
In some cases, Some browsers cache the results of multiple XMLHttpRequest requests in the same URL. If the response to each request is different, this will bring bad results. append the current timestamp to the end of the URL to ensure the uniqueness of the URL, so as to avoid the browser caching the results.
In this example, the server code uses asp.net (c #).
DoRequestUsingPOST ()Send a request to the server in http post mode and pass parameters.
Make sure that the method specified in open () is POST. You need to set the Content-Type header and simulate the http post method to send a form so that the server will know how to process the uploaded Content. You must call the open method before setting the header information.
Parameters must be passed using the send method. The parameter submission format is the same as that in the GET method.
HandleStateChange ()Ajax callback function.
For XMLHttpRequest objects, the onreadystatechange attribute stores the pointer of the callback function. This callback function is called when the internal status of the XMLHttpRequest object changes.
ParseResults ()Process the response.

The above is a simple Ajax request instance. You are welcome to learn and download the Ajax request instance.

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.