//创建 XMLHttpRequest 对象var xhr = new XMLHttpRequest();//兼容写法var xhr = null;if (window.XMLHttpRequest){// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码xhr=new XMLHttpRequest();}else{// IE6, IE5 浏览器执行代码xhr=new ActiveXObject("Microsoft.XMLHTTP");}
get请求方式
//准备发送xhr.open("GET","url" + "userName=" + username,true); //请求方式,请求地址,是否异步(默认为true,异步请求)//执行发送xhr.send(null)
post请求方式
//准备发送xmlhttp.open("POST","请求地址",true);//请求头xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//参数var param = "userName=" + userName;//请求体 执行发送xmlhttp.send(param);
//通过回调函数,获取数据xhr.onreadystatechange=function(){if (xhr.readyState==4 && xhr.status==200){var result = xhr.responseText;}}
function Ajax(type,url,params,dataType,callback){//创建 XMLHttpRequest 对象var xhr = new XMLHttpRequest();//准备发送if(type == "get"){if(params && params != ""){url = url + "?" + params;}}xhr.open(type,url,true);//执行发送if(type == "get"){xhr.send(null);}else if(type == "post"){xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");xhr.send(params);}//通过回调函数,获取数据xhr.onreadystatechange=function(){if (xhr.readyState==4 && xhr.status==200){var result = null;if(dataType == "json"){result = xhr.responseText; //返回字符串result = JSON.parse(result); //json格式化数据}else if(dataType == "xml"){result = xhr.responseXML;}else{result = xhr.responseText;}if(callback){callback(result);}}}}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号