以下是最原始的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(同步)方式的回调函数不起作用
本文详细介绍了JavaScript的AJAX基本实现方法,包括GET和POST方式的使用,以及如何通过回调函数处理服务器响应。特别指出在Firefox中同步方式的回调函数可能无法正常工作。
450

被折叠的 条评论
为什么被折叠?



