Home > Web Front-end > JS Tutorial > body text

Sharing of javascript native ajax writing methods_javascript skills

WBOY
Release: 2016-05-16 15:06:13
Original
1536 people have browsed it

ajax: a way to request data without refreshing the entire page;
The technical core of ajax is the XMLHttpRequest object;
ajax request process: create XMLHttpRequest object, connect to server, send request, receive response data;

/**
 * 得到ajax对象
 */
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以上
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        alert("您的浏览器不支持AJAX!");
        return false;
      }
    }
  }
  return xmlHttp;
}
/**
 * 发送ajax请求
 * url--url
 * methodtype(post/get)
 * con (true(异步)|false(同步))
 * parameter(参数)
 * functionName(回调方法名,不需要引号,这里只有成功的时候才调用)
 * (注意:这方法有二个参数,一个就是xmlhttp,一个就是要处理的对象)
 * obj需要到回调方法中处理的对象
 */
function ajaxrequest(url,methodtype,con,parameter,functionName,obj){
  var xmlhttp=getajaxHttp();
  xmlhttp.onreadystatechange=function(){
     
    // readyState值说明 
    // 0,初始化,XHR对象已经创建,还未执行open 
    // 1,载入,已经调用open方法,但是还没发送请求 
    // 2,载入完成,请求已经发送完成 
    // 3,交互,可以接收到部分数据 
  
    // status值说明 
    // 200:成功 
    // 404:没有发现文件、查询或URl 
    // 500:服务器产生内部错误 
 
    if(xmlhttp.readyState==4&& XHR.status == 200){
      //HTTP响应已经完全接收才调用
      functionName(xmlhttp,obj);
    }
  };
  xmlhttp.open(methodtype,url,con);
  xmlhttp.send(parameter);
}
//这就是参数
function createxml(){
  var xml="<user><userid>asdfasdfasdf<\/userid><\/user>";//"\/"这不是大写V而是转义是左斜杠和右斜杠
  return xml;
}
//这就是参数
function createjson(){
  var json={id:0,username:"好人"};
  return json;
}
function c(){
  alert("");
}
Copy after login

//Test

ajaxrequest("http://www.baidu.com","post",true,createxml(),c,document);
Copy after login

Let’s look at another example

ajax({
    url: "./TestXHR.aspx",       //请求地址
    type: "POST",            //请求方式
    data: { name: "super", age: 20 },    //请求参数
    dataType: "json",
    success: function (response, xml) {
      // 此处放成功后执行的代码
    },
    fail: function (status) {
      // 此处放失败后执行的代码
    }
  });

  function ajax(options) {
    options = options || {};
    options.type = (options.type || "GET").toUpperCase();
    options.dataType = options.dataType || "json";
    var params = formatParams(options.data);

    //创建 - 非IE6 - 第一步
    if (window.XMLHttpRequest) {
      var xhr = new XMLHttpRequest();
    } else { //IE6及其以下版本浏览器
      var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }

    //接收 - 第三步
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        var status = xhr.status;
        if (status >= 200 && status < 300) {
          options.success && options.success(xhr.responseText, xhr.responseXML);
        } else {
          options.fail && options.fail(status);
        }
      }
    }

    //连接 和 发送 - 第二步
    if (options.type == "GET") {
      xhr.open("GET", options.url + "&#63;" + params, true);
      xhr.send(null);
    } else if (options.type == "POST") {
      xhr.open("POST", options.url, true);
      //设置表单提交时的内容类型
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.send(params);
    }
  }
  //格式化参数
  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("&");
  }
Copy after login

Let’s take a look at the principle

1. Create

1.1, IE7 and above support native XHR objects, so you can use it directly: var oAjax = new XMLHttpRequest();

In 1.2, IE6 and previous versions, the XHR object is implemented through an ActiveX object in the MSXML library. Some books detail three different versions of such objects in IE, namely MSXML2. =new ActiveXObject('Microsoft.XMLHTTP');

2. Connect and send

2.1. Three parameters of the open() function: request method, request address, and whether to request asynchronously (synchronous requests are rare and have not been used so far);

2.2. The GET request method submits data to the server through URL parameters, while POST submits data to the server as send parameters;

2.3. In POST request, before sending data, the content type of form submission must be set;

2.4. Parameters submitted to the server must be encoded through the encodeURIComponent() method. In fact, in the parameter list "key=value", both key and value need to be encoded because they will contain special characters. Each time a request is made, a "v=xx" string will be spelled into the parameter list. This is to refuse caching and request directly to the server every time.

encodeURI(): used for encoding the entire URI. Special characters that are part of the URI will not be encoded, such as colons, forward slashes, question marks, and pound signs; its corresponding decoding function decodeURI();
encodeURIComponent(): used to encode a certain part of the URI, and will encode any non-standard characters it finds; its corresponding decoding function decodeURIComponent();

3. Receive

3.1. After receiving the response, the response data will automatically fill in the XHR object. The relevant attributes are as follows
responseText: the body content returned by the response, which is a string type;
responseXML: If the content type of the response is "text/xml" or "application/xml", this attribute will store the corresponding xml data, which is the document type corresponding to XML;
status: response HTTP status code;
statusText: Description of HTTP status;

3.2. The readyState attribute of the XHR object indicates the current active stage of the request/response process. The value of this attribute is as follows
0 - Not initialized, the open() method has not been called;
1-Start up, the open() method is called, the send() method is not called;
2-Send, the send() method has been called, and no response has been received;
3-Receive, part of the response data has been received;
4-Complete, all response data has been received;

As long as the value of readyState changes, the readystatechange event will be called. (In fact, for logical smoothness, readystatechange can be placed after send, because when sending, requesting the server will cause network communication, which takes time. Specify the readystatechange event after send. Handlers are also possible, I usually use them this way, but for the sake of standardization and cross-browser compatibility, it is better to specify them before opening).

3.3. In the readystatechange event, first determine whether the response is received, and then determine whether the server successfully processed the request. xhr.status is the status code. Status codes starting with 2 are successful. 304 means getting it from the cache. The code adds a random number to each request, so the value will not be retrieved from the cache, so there is no need to judge this status.

4. Ajax requests cannot cross domains!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template