日期:2014-05-16  浏览次数:20344 次

javascript中ajax的基本用法

?

以下是最原始的javascript的ajax方式代码,有get和post两种方式

var xmlHttpRequest=null;

function ajaxSubmit(){

if(window.ActiveXObject)//是IE浏览器

{

xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");

}

else if(window.XMLHttpRequest)//是除IE外的其他浏览器

{

xmlHttpRequest=new XMLHttpRequest();

}

if(null!=xmlHttpRequest){

//get方式提交,GET为提交方式,testServlet为提交地址,true为异步,false为同步,GET方式提交,附加参数只能跟在地址的后边

xmlHttpRequest.open("GET","testServlet?name=twy",true);

//关联回调函数

xmlHttpRequest.onreadystatechange=ajaxCallback;

//向服务器发送数据

xmlHttpRequest.send(null);

/** ?post方式提交,附加参数可以写在send方法中

xmlHttpRequest.open("POST","testServlet",true);

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

xmlHttpRequest.send("name=twy");

**/

}

}

? ? ? ? ? ? ? ? //回调函数

function ajaxCallback(){

? ? ? ? ? ? ? ? ? ? ? ? //0未连接,1打开连接,2发送请求,3交互,4完成交互,接收相应

if(xmlHttpRequest.readyState==4){? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

if(xmlHttpRequest.status==200){

var responseText=xmlHttpRequest.responseText;

alert(responseText);

}

}

}

在火狐里,false(同步)方式的回调函数不起作用

?

?

?