天天看點

Ajax

什麼是Ajax:

  Asyschronous JavaScript And XML(異步JS與XML技術),是一種廣泛應用在浏覽器的網頁開發技術。它是由Jesse James Garrett提出。

 Ajax中最主要對象是XMLHttpRequest ,JS可以直接通過它來與伺服器進行通信,通過這個對象,JS在一重載頁面的情況下與Web伺服器交換資料。

Ajax的二種送出方式(GET、POST)的模型和XMLHttpRequest對象的浏覽器支援代碼及後面Servlet處理的中文字元編碼處理。

一、XMLHttpRequest在多浏覽器中擷取

function createXHR(){

    if(typeof window.XMLHttpRequest!="undefined"){

       return new XMLHttpRequest();

}else if(window.ActiveXoBJECT!="undefined"){

   var vessions = ["MSXML2.XMLHttp6.0","MSXML2.XMLHttp3.0","MSXML2.XMLHttp"];

  for(var i=0;i<versions.length;i++){

   try{

     var xhr=new ActiveXObject(vesionss[i]);

}catch(e){}

}else{

   throw newError("沒有找到相容的浏覽器");

}

二、GET方式和POST方式處理代碼:

function byget(){

   var xhr=createXHR();

   xhr.onreadystatechange=function(){

   if(xhr.readyState==4&&xhr.status==200){

    //處理代碼   .innerHTML=xhr.responseText;

   //它傳回有responseXML  和responseText  二個主要的對象

  url="路徑?username="+username;

 url=encodeURI(url);//處理編碼

xhr.open("GET",url,true);//true為允許異步方式

xhr.send(null);

POST方式

function bypost(){

  var xhr=createXHR();

xhr.onreadystatechange=function(){

    //處理代碼

document.getElementById(id).innerHTML-xhr.responseText;

url="路徑";

xhr.open("POST",url,true);

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

var data=encodeURI("username="+val+"&pwd="+password);

xhr.send(data);

}}

三、servlet處理代碼

doGet(req,resp){

String username=req.getParameter("username");

username=new String(username.getByte("iso-8859-1"),"utf-8");

resp.setCharacterEncoding("utf-8");

 resp.setHeader("Content-Type", "text/html; charset=UTF-8");

 PrintWriter writer = resp.getWriter();

 writer.print("hello"+username);

doPost(req,resp){

PrintWriter writer=resp.getWriter();

req.setCharacterEncoding("utf-8");

writer.println("hello"+username);

req.setCharacter