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(){

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

    //處理代碼

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){

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

PrintWriter writer=resp.getWriter();

req.setCharacterEncoding("utf-8");

writer.println("hello"+username);

req.setCharacter

 

}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章