欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最简单的ajax例子

程序员文章站 2022-04-13 08:48:58
...
var xmlHttpReq; 
//创建XMLHTTP对象
function createXMLHttpRequest(){
if(window.ActiveXObject){ // IE,//如果浏览器支持window.ActiveXObject对象
xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP.3.0");
var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
try {
xmlHttpReq= new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}

}else if(window.XMLHttpRequest){ // Mozilla, Safari, ...
xmlHttpReq = new XMLHttpRequest();
}
}

function getXmlSend(flag,id){
IDflag=flag;
createXMLHttpRequest();
var url="/.../xx.jsp?rand=" + Math.random() + "&id="+id+"&flag="+flag;
xmlHttpReq.open("GET",url,true);
//xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
xmlHttpReq.onreadystatechange = showResult; //异步调用showResult方法
xmlHttpReq.send(null); // 开始发起浏览请求, Mozilla 必须加 null
/*
同步的做法是:屏蔽掉上面xmlHttpReq.onreadystatechange = showResult;同时xmlHttpReq.open("GET",url,false);
接着直接在 http_request.send(null);下面获得结果
var returntxt=unescape(http_request.responseText);

post 的提交做法
xmlHttpReq.open("POST",url,true);
xmlHttpReq.send("这里是需要传的参数"); //eg:rand=" + Math.random() + "&id="+id+"&flag="+flag
*/
}

function showResult(){
if(xmlHttpReq.readyState == 4){
if(xmlHttpReq.status == 200){
alert(xmlHttpReq.responseText);
// 更新对应的 HTML 元素里面显示的内容
//do something
}
}
}


页面或其他地方就调用getXmlSend()方法就可以了