JavaScript Ajax Programming Application Article _javascript skill

Source: Internet
Author: User

First, Ajax (Asynchronous JavaScript + XML) can request additional data like a server without unloading the page, that is, the local brush new technology
Second, create a XHR object

 function createxhr () {
 if (typeof XMLHttpRequest!= "undefined") {return
  new XMLHttpRequest ();
 } else if (Ty peof activexobject!= "undefined") {//< Ie7 
  if (typeof arguments.callee.activeXString!= "string") {
  var vers Ion = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", "MSXML2". XMLHttp "],
   I, Len;
  for (i = 0, len = version.length i < len; i++) {
   try { 
   new ActiveXObject (version[i));
   arguments.callee.activeXString = Version[i];
   break;
   catch (ex) {}}} return
  new ActiveXObject (arguments.callee.activeXString);
 } else {
  throw New Error ("No Support for XHR");
 }
 var xhr = createxhr ();
 alert (XHR); [Object XMLHttpRequest]

Iii. Usage Note: The examples in this section apply to server-side
1. Call the Open () method. It accepts 3 parameters: the type of request to send ("get", "post", and so on), the URL of the request, and the Boolean value that represents whether the request was sent asynchronously.
2. To send a request, call the Send () method and accept a parameter, which is the body to send as a request. Null if not required
3. The returned data is automatically populated into the properties of the Xhr object.

 var xhr = createxhr ();
 Get-mode open Example.txt file
 //sync: JavaScript code waits for a response from the server
 to execute xhr.open (' Get ', ' example.txt ', false);
 Xhr.send (null);
 The status represents the HTTP status of the response
 //200 for ok,304 represents the cache
 if ((Xhr.status >= && xhr.status <) | | xhr.status = = 304) {
  alert (xhr.responsetext);//Return the text of the response, 123456
 } else {
  alert ("Request was unsuccessful:" + xhr.status);
 }

4.example.text file content is string: 123456

Four, the previous use of the synchronized way, of course, there will be no problems, all of us to challenge an asynchronous method.

 var xhr = CREATEXHR (); 
//Xhr.readystate indicates the current state of the request/response, 4 delegates have accepted all response data//And as long as Xhr.rea The Dystate value has changed, then the Xhr.onreadystatechange event triggers the Xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {if (xhr. Status >= && xhr.status < 300) | | Xhr.status = = 304) {alert (xhr.responsetext); else {alert ("Request was unsuccessful:" + xhr.status); } } }; Xhr.open ("Get", "Example.txt", true); Xhr.send (NULL);

Five, each HTTP request and response will have the corresponding header information
    1. By default, the following header information is sent as well as the XHR request.
       ①accept: The type of content that the browser can handle.
       ②accept-charset: The character set that the browser can display.
       ③accept-encoding: The compression code that the browser can handle.
       ④accept-language: The language currently set by the browser.
       ⑤connection: The type of connection between the browser and the server.
       ⑥cookie: Any Cookie that is set on the current page.
       ⑦host: The domain of the page where the request is made.
       ⑧referer: The URI of the page that issued the request.
       ⑨user-agent: The user agent string for the browser.
    2. Use the setRequestHeader () method to set custom request header information. Accept two parameters: the name of the header field and the value of the header field       

 var xhr = createxhr ();
 Xhr.readystate represents the current state of the request/response, 4 delegates have accepted all response data
 //And as long as the Xhr.readystate value has changed, the Xhr.onreadystatechange event triggers
 Xhr.onreadystatechange = function () {
  if (xhr.readystate = 4) {
  if (xhr.status >= && Xhr.status < 300) | | Xhr.status = = 304) {
   alert (xhr.responsetext);
  } else {
   alert ("Request was unsuccessful:" + Xhr.status);
  }
  }
 };
 Xhr.open ("Get", "Example.txt", true);
 The
 xhr.setrequestheader ("name", "Zhang") must be called after open (), and//the accepted "name" can be seen in Example.txt http: "Zhang"
 Xhr.send (NULL);

3. Get the requested header information and corresponding information, call the getResponseHeader () method getAllResponseHeaders () method

 var xhr = createxhr ();
 Xhr.readystate represents the current state of the request/response, 4 delegates have accepted all response data
 //And as long as the Xhr.readystate value has changed, the Xhr.onreadystatechange event triggers
 Xhr.onreadystatechange = function () {
  if (xhr.readystate = 4) {
  if (xhr.status >= && Xhr.status < 300) | | Xhr.status = = 304) {
   //Get response header's Content-type
   var connection = Xhr.getresponseheader ("Content-type");
   alert (connection); Text/plain
   //Get all the response information
   var all = Xhr.getallresponseheaders ();
   alert (All);
  } else {
   alert ("Request was unsuccessful:" + Xhr.status);
  }
  }
 ;
 Xhr.open ("Get", "Example.txt", true);
 Xhr.send (NULL);

Six, GET request, we have discussed the method of getting request, now let's expand, add some parameters for getting request

/** URL: url with no request name: Request Key value: Request value return: URL with request string/function Addurlpar AM (URL, name, value) {url = = (Url.indexof ("?") = = 1?
 "?": "&");
 URL + encodeuricomponent (name) + "=" + encodeuricomponent (value);
 return URL;
 var xhr = createxhr (); Xhr.onreadystatechange = function () {if (xhr.readystate = 4) {if (xhr.status >= && Xhr.status < 300 ) ||
  Xhr.status = = 304) {alert (xhr.responsetext);
  else {alert ("Request was unsuccessful:" + xhr.status);
 }
 }
 };
 var url = "Example.txt";
 url = addurlparam (URL, "name", "Zhang");
 url = addurlparam (URL, "age", "23");
 The requested URL becomes: example.txt?name=zhang&age=23 xhr.open ("Get", url, True);
Xhr.send (NULL); 

Seven, POST request
    1. Case study: Next we discuss an AJAX application that sends a request by post, that is, user registration, which returns a hint based on your registered username.
    2. Implementation steps
        1 The first thing to have is a registered page (which, of course, is simple) ajax.html          

 <! DOCTYPE html>  
 

2) Then of course the JavaScript part
①eventutil.js, here's just a list of the events listening.

 var eventutil = {
   addevent:function (element, type, handler) {
   if (Element.addeventlistener)
   {
    element . AddEventListener (Type, handler, false);
   else if (element.attachevent)
   {
    element.attachevent ("on" + type, handler);
   }
   }
  

②serialize.js: Form serialization

 function serialize (form) {var parts = [], field = null, I, Len, J, optlen, option, Optvalue;
   For (i=0, len=form.elements.length i < Len; i++) {field = Form.elements[i]; Switch (field.type) {case ' Select-one ': Case ' select-multiple ': if (field.name.length) {for (j=0, Optlen = Field.options.length; J < Optlen;
     J + +) {option = Field.options[j];
     if (option.selected) {optvalue = "";
      if (option.hasattribute) {Optvalue = (Option.hasattribute ("value")?
     Option.value:option.text);
      else {Optvalue = (option.attributes["value"].specified?)
     Option.value:option.text);
     } parts.push (encodeURIComponent (field.name) + "=" + encodeURIComponent (optvalue));
    }} break; Case undefined://field set case "file"://File input case "submit"://Submission button case "reset"://Reset button Case "button"://Custom Press
    button break;
    Case "Radio"://radio button case "checkbox"://check box if (!field.checked) {Break /* Perform the default action/\ n://Does not contain a form field without a name if (field.name.length) {Parts.push (encodeuricomponent) (Field.nam
    E) + "=" + encodeURIComponent (field.value));
  }} return Parts.join ("&");
 }

           ③ajax.js, which is the CREATEXHR () function above, is not listed here. The
           ④ajaxdo.js, the core file, is our operating part, the name is scribbled.
              

 var form = document.forms[0];//Get form var username = form.elements[' username '];//username var Userlabel = document.queryselector ("#userLabel");
   Prompt label eventutil.addevent (username, "blur", function () {var xhr = createxhr ();  Xhr.onreadystatechange = function () {if (xhr.readystate = 4) {if (xhr.status >= && Xhr.status < 300) | |
    Xhr.status = = 304) {var text = Xhr.responsetext;
     When true, prompts for green font//When false, prompts for red font if (text) {UserLabel.style.color = "green";
    UserLabel.firstChild.data = "Congratulations, user name available";
     else {userLabel.style.color = "red";
    UserLabel.firstChild.data = "Sorry, the user already exists";
    } else {alert ("Request was unsuccessful:" + xhr.status);
   }
   }
   };
   Post request Xhr.open ("Post", "dome.php", true);
   Submitted content Type Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
  Serializes the form xhr.send (form); serialize
}); 

3. Improvements: As you can see, we've serialized the form when we submitted the form. At XMLHttpRequest Level 2 This defines the Formdata type, which automatically serializes the form for us and does not need to be written by ourselves.
We only move part of the code.

 // ... This omits the code and the above consistent
 //POST request
 Xhr.open ("Post", "dome.php", true);
 This only needs to be changed to replace the function
 xhr.send (new FormData form) in the previous serialize.js.

Viii. other parts (understand, because compatibility is not enough)
1. Timeout setting

 Xhr.open ("Get", "Example.txt", true);
 xhr.timeout = 1000; Set timeout to 1 seconds (ie8+ only)
 xhr.ontimeout = function () {
 alert ("Request did not return in a second.");
 Xhr.send (NULL);

2.overrideMimeType () method, for the type returned by the server

 var xhr = createxhr ();
 Xhr.open ("Get", "Example.txt", true);
 Xhr.overridemimetype ("Text/xml"); The previous is Text/plain
 xhr.send (null);

3. Progress Events
1.load event, as long as the browser receives information on the server to trigger

 var xhr = createxhr ();
  Xhr.onload = function () {
  if (xhr.status >= && xhr.status <) | | xhr.status = = 304) {
   alert (XH R.responsetext);
  } else {
   alert ("Request was unsuccessful:" + Xhr.status);
  }
  ;
  Xhr.open ("Get", "Example.txt", true);
  Xhr.send (NULL);

2.progress event, which periodically triggers the browser to receive new data

 var xhr = createxhr ();
  xhr.onprogress = function (event) {
  var divstatus = document.getElementById ("status");
  Calculates the percentage of data that has been received from the response
  if (event.lengthcomputable) {
   divstatus.innerhtml = "Received" + event.position + "of" +
   event.totalsize + "bytes";
  }
  ;
  Xhr.open ("Get", "altevents.php", true);
  Xhr.send (NULL);

The above is the entire content of this article, I hope to help you learn.

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.