Ajax

来源:互联网 发布:九子夺嫡 知乎 编辑:程序博客网 时间:2024/04/28 23:18

什么是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

 

}

 

 

 

本文出自 “Vickyi_” 博客,请务必保留此出处http://vickyi.blog.51cto.com/1367214/964493

原创粉丝点击