JavaScript native Ajax notation sharing _javascript Skills

Source: Internet
Author: User

Ajax: A way to request data without refreshing the entire page;
The technology core of Ajax is the XMLHttpRequest object;
Ajax request Process: Create XMLHttpRequest object, connect server, send request, receive response data;

/** * Get Ajax object/function Getajaxhttp () {var xmlHttp;
    try {//chrome, Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest (); catch (E) {//Internet Explorer try {//ie5,6 xmlHttp = new ActiveXObject ("Msxml2.xmlhttp")
      ;
      catch (e) {try {//ie7 above xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP"); catch (E) {alert ("Your browser does not support ajax!
        ");
      return false;
}} return xmlHttp; /** * Send AJAX Request * Url--url * METHODTYPE (post/get) * Con (True (asynchronous) |false (sync)) * parameter (parameter) * functionname (callback method name, no Need quotes, here only when successful call) * (Note: This method has two parameters, one is XMLHTTP, one is the object to be processed) * obj needs to be processed in the callback method/function Ajaxrequest (Url,methodtype,
  Con,parameter,functionname,obj) {var xmlhttp=getajaxhttp (); Xmlhttp.onreadystatechange=function () {//ReadyState value Description//0, initialization, XHR object has been created, open//1 has not been executed, loading, the open method has been called 
   , but has not sent the request//2, loading completed, the request has been sent to complete//3, interactive, can receive some data//Status Value description 200: Success//404: No file found, query or URL//500: Server generates internal error if (xmlhttp.readystate==4&& xhr.status = = 200) {
    HTTP response has been fully received before calling functionname (Xmlhttp,obj);
  }
  };
  Xmlhttp.open (Methodtype,url,con);
Xmlhttp.send (parameter); //This is the parameter function Createxml () {var xml= "<user><userid>asdfasdfasdf<\/userid><\/user>" \
/"This is not a capital V but an escape is a left slash and a right slash return XML;"
  //This is the parameter function Createjson () {var json={id:0,username: "Good guy"};
return JSON;
 Function C () {alert ("");}

Test

Ajaxrequest ("http://www.baidu.com", "Post", True,createxml (), c,document);

Let's take another look at an example

Ajax ({URL: "./testxhr.aspx",//Request Address Type: "POST",//Request method data: {name: "Super", age:20}, Request parameter DataType: "JSON", success:function (response, XML) {//code executed after success}, Fail:function (St

  ATUs) {//Here is the code to execute after failure}}); function Ajax (options) {options = Options | |
    {}; Options.type = (Options.type | |
    "Get"). toUpperCase (); Options.datatype = Options.datatype | |
    "JSON";

    var params = Formatparams (Options.data); Create-Non IE6-first step if window.
    XMLHttpRequest) {var xhr = new XMLHttpRequest ();
    else {//IE6 and the following version of browser var xhr = new ActiveXObject (' microsoft.xmlhttp '); //Receive-third Step xhr.onreadystatechange = function () {if (xhr.readystate = 4) {var status = Xhr.sta
        Tus if (Status >= && status <) {options.success && options.success (Xhr.responsetext,
        Xhr.responsexml); else {Options.fail &AMP;&Amp
        Options.fail (status); }}//Connect and send-second step if (Options.type = = "Get") {Xhr.open ("get", Options.url + "?" + params, tr
      UE);
    Xhr.send (NULL);
      else if (Options.type = = "Post") {Xhr.open ("post", Options.url, True);
      Set the content type for form submission Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
    Xhr.send (params);
    }///format parameter function formatparams (data) {var arr = [];
    for (var name in data) {Arr.push (encodeURIComponent (name) + "=" + encodeURIComponent (data[name));
    } Arr.push (("v=" + math.random ()). Replace (".", ""));
  Return Arr.join ("&");
 }

Let's see how it works.

1, create

1.1, IE7 and the above version to support the native XHR objects, so you can directly use: var Oajax = new XMLHttpRequest ();

1.2, IE6 and its previous versions, the XHR object is implemented through an ActiveX object in the MSXML library. In some books, there are three different versions of such objects in IE, namely Msxml2.xmlhttp, msxml2.xmlhttp.3.0 and msxml2.xmlhttp.6.0; personal feeling too troublesome, you can directly use the following statement to create: Var oajax=new ActiveXObject (' microsoft.xmlhttp ');

2. Connect and send

2.1, the Open () function of three parameters: the request method, the request address, whether asynchronous request (synchronous request is very rare, so far has not been used);

2.2, GET request way is through the URL parameter to submit the data to the server, post is by the data as send parameters submitted to the server;

2.3, the POST request, before sending the data, to set the form submitted content type;

2.4, the parameters submitted to the server must be encoded by the encodeURIComponent () method, in fact, in the form of the parameter list "Key=value", key and value need to be encoded, because it will contain special characters. A "v=xx" string is spelled in the parameter list each time the request is requested, so that the cache is rejected, and the server is directly requested each time.

encodeURI (): For encoding the entire URI, does not encode special characters that are part of the URI, such as colons, forward slashes, question marks, and well numbers, and their corresponding decoding functions decodeURI ();
encodeURIComponent (): Used to encode a part of a URI, to encode any non-standard characters it finds, and its corresponding decoding function decodeuricomponent ();

3, receive

3.1, after receiving the response, the response data will automatically populate the Xhr object, the related properties are as follows
ResponseText: The body content returned by the response, is a string type;
Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the corresponding XML data, which is the corresponding document type of XML;
Status: The HTTP status code of the response;
Description of the statustext:http state;

3.2. The ReadyState property of the Xhr object represents the current active phase of the request/response process, and the value of this property is as follows
0-Uninitialized, the open () method has not been invoked;
1-starts, calls the open () method, does not call the Send () method;
2-Send, has called the Send () method, did not receive a response;
3-Receive, has received partial response data;
4-Complete, has received the full response data;

As long as the value of the readyState changes, it will invoke the ReadyStateChange event, (in fact, in order to logically fluent, you can put the readystatechange after send, because the Send request server, will be network communication, takes time, It is also OK to specify the ReadyStateChange event handler after send, which I usually do, but specify before open for specification and Cross-browser compatibility.

3.3, in the ReadyStateChange event, first to determine whether the response received completed, and then determine whether the server successfully processed the request, Xhr.status is the status code, the status code to start with 2 is a success, 304 for the cache to get, The above code adds random numbers to each request, so no value is taken from the cache, so the state does not need to be judged.

4, the AJAX request is not Cross-domain!

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.