Very simple ajax request instance with source code

Time:2020-11-22

AJAX is not a new programming language, but a technology for creating better, faster and more interactive web applications. With Ajax, you can use JavaScript’s XMLHttpRequest object to communicate directly with the server. You can exchange data with the web server without overloading the page. In this example, we will demonstrate how a web page communicates with a web server when a user enters 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
 <script type="text/javascript">
  var xmlHttp;
  //Creating an XMLHttpRequest object
  function createXMLHttpRequest() {
   if (window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   else if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
   }
  }
  //Integrating URL parameters
  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 parameters as get
  function doRequestUsingGET() {
   createXMLHttpRequest();
   var queryString = "AjaxServer.ashx?";
   queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime();
   xmlHttp.onreadystatechange = handleStateChange;
   xmlHttp.open("GET", queryString, true);
   xmlHttp.send(null);
  }
  //Pass parameters by post
  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
  function handleStateChange() {
   if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
     parseResults();
    }
   }
  }
  //Processing 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>
</head>
<body>
 <form action="#">
 <h2>Enter your name, gender, birthday:</h2>
 <table>
  < tr > < td > Name: < / td > < td > < input type = "text" / > < / td > < / TR >
  < tr > < td > gender: < / td > < td > < input type = "text" / > < / td > < / TR >
  < tr > < td > birthday: < / td > < td > < input type = "text" / ></td>
  </tr>
 </table>
 < input type = button "value = pass parameters in get mode" onclick = "dorequest usinget();" / >
 <br /><br />
 < input type = "button" value = passing parameters by post "onclick =" dorequest usingpost(); "/ >
 </form>
 <br />
 <h3>Server response content:</h3>
 <div></div>
</body>
</html>

The following is a detailed description of the functions of each JS function.
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. Because of these differences, the relevant logic must be included in the JavaScript code.
createQueryString() It is used to organize the parameters to be passed by Ajax requests into a certain format.
If the Chinese or non ASCII characters must be URL encoded, this example uses the encoding component() function of JS to encode the parameter URL.
doRequestUsingGET() Send the request to the server in the form of HTTP get, and pass the parameters.
The open () method of the XMLHttpRequest object specifies the request that will be issued. The open() method takes three parameters: a string indicating the method used (usually get or post); a string representing the URL of the target resource; and a Boolean value, which only indicates whether the request is asynchronous.
In the get request, the parameter passed is written to the URL parameter of the open method, and 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 lead to bad results. Appending the current timestamp to the end of the URL can ensure the uniqueness of the URL, thus avoiding the browser from caching the results.
In this example, the server-side code uses asp.net (c#)。
doRequestUsingPOST()Send the request to the server in HTTP post mode, and pass the parameters.
To ensure that the method specified in open() is post, you need to set the content type header and send a form by simulating the HTTP post method, so that the server will know how to handle the uploaded content. The open method must be called before setting the header.
You must pass parameters using the send method. Parameters are submitted in the same format as the URL in the get method.
handleStateChange()  Ajax callback function.
For the XMLHttpRequest object, the onreadystatechange property stores the pointer to the callback function. This callback function is called when the internal state of the XMLHttpRequest object changes.
parseResults() Process response results.

The above is a very simple ajax request example, welcome to learn, downloadAjax request instance