温故Ajax入门基础

一、Ajax的相关知识点:

   1.如何创建XMLHttpRequest对象?
     注:这与浏览器的版本有关,window.ActiveXObject 若返回对象,则条件为true,否则为false
     a. if (window.ActiveXObject) --> xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     b. if (window.XMLHttpRequest) --> xmlhttp = new XMLHttpRequest();

   2.XMLHttpRequest对象的相关方法和属性

     方法:
     a. abort(); --> 停止当前请求
     b. getAllResponseHeaders() --> 把Http的所有请求响应首部作为键/值对返回;
     b. getResponseHeader(header) --> 返回指定首部的串值;
     c. open(method,url,boolean,username,password)--> 建立对服务器的调用,method表示请求方法,
        url 表示请求资源(jsp,html,serlvet,xml,txt),boolean表示是否同步(若为true,则异步执行,若为false,则为同步(即上
一步未完成,则下一步不会执行,在默认情况下为异步的),username和password表示用户名和密码
注:后三个参数为可选参数。
     d. setRequestHeader("header","value");设置首部的值,该方调用必须在open()之后;
     e. send(context);向服务器发送请求;若为POST请求,则context为请求参数,若为GET请求则context为空!

     属性:
     a. onreadystatechange 这是一个事件,每改变一个状态都会触发该事件;
     b. readyState 表示状态 有5个可取值:0=未初始化,1=正在加载,2=已加载,3=交互中,4=完成
     c. responseText 来自服务器的文本响应;
     d. responseXML 返回一个DOM对象;
     e. status 服务器的Http状态码(200对应(OK),404对应Not Found(未找到),等等);
     f. statusText 表示状态码对应文本;
   
二、用Ajax开发Web程序的一般步骤:
    
    1.客户端
      a. 实例化一个全局的XMLHttpRequest对象
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      b. 为xmlhttp的onreadystatechange事件绑定一个函数
         xmlhttp.onreadystatechange = function(){};
      c. 建立对服务器的调用
         xmlhttp.open(method,url);
      d. 禁用客户端缓存
         xmlhttp.setRequestHeader("Cache-Control","no-cache");
      e. 正式发送请求
         xmlhttp.send();

      补充:若请求为POST,则需要设置Content-Type首部 
         xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     
    2.服务器端
      a.设置编码方式(并非一定);

        request.setCharacterEncoding("encoding");

        response.setCharacterEncoding("encoding");


      b.设置客户端响应输出方式(取决于responseText 和 responseXML)
        response.setContentType("text/xml;character=utf-8");
        或response.setContentType("text/html;character=utf-8");
      
      c.禁用缓存
        response.setHeader("pragma", "no-cache");

        response.setHeader("cache-control", "no-cache");

        response.setDateHeader("expires",0);


原文地址:https://www.cnblogs.com/yyuuaannllii/p/3775218.html