AJAX--XMLHttpRequset用法
Ajax=Asynchronous JavaScript and XML(异步的 JavaScript 和 XML),而XMLHTTPRequest 是Ajax的基础,所有的浏览器都支持XMLHTTPRequest 对象(IE5 和 IE6 使用 ActiveXObject)。
1、根据浏览器版本创建XMLHtppRequset对象。
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
if(xmlhttp.overrideMimeType)
{
xmlhttp.overrideMimeType("text/xml");
}
}
else if(window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp==undefined||xmlhttp==null)
{
alert("不支持XMLHttpRequest对象");
}
//设置交互方式
xmlhttp.open("GET","1.json",true);
//xmlhttp.open("POST","1.json",true);
//xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//发送数据开始和服务端交互。
xmlhttp.send();
//判断和服务器端的交互是否完成,还要判断服务器端是否正确返回了数据
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState == 4){
//表示和服务器端的交互已经完成
if(xmlhttp.status == 200){
//表示服务器的是响应代码是200,正确返回了数据
var message=xmlhttp.responseText;
//XML数据对应的DOM对象的接受方法
//使用的前提是,服务器端需要设置contenttype为text/xml
//记忆像div标签中填充文本内容的方法
var div=document.getElementById("message");
div.innerHTML=message;
alert(message);
}
}
}
浙公网安备 33010602011771号