ajax.js
向服务器发送请求
//对象转字符串
function objToStr(obj){
obj.t = new Date().getTime();
var res = [];
for (var key in obj) {
//防止url中出现中文,如果有中文,需要转码
//调用encodeURIComponent()方法
//URL中只能出现字母、数字、下划线、ASCII码
res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]));
}
return res.join("&");
}
function ajax(type,url,obj,timeout,success,error){
//0.将json对象转为字符串
var str = objToStr(obj);//格式为:key=value&key=value;
//1.创建一个异步对象
var xmlhttp,timer;
if (window.XMLHttpRequest) {//code for IE7+,firefox,chrome,opera,safari
xmlhttp = new XMLHttpRequest();
} else {//code for IE6,IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.设置请求方式和请求地址
if (type.toLowerCase === "get") {
//2.设置请求方式和请求地址
xmlhttp.open(type,url+"?"+str,true);
//3.发送请求
xmlhttp.send();
} else {
xmlhttp.open(type,url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//3.发送请求
xmlhttp.send(str);
}
//4.监听状态变化
xmlhttp.onreadystatechange = function(){
/*
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完毕,且响应已就绪
*/
if (xmlhttp.readyState === 4) {
clearInterval(timer);
//判断是否请求成功
if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
//5.处理返回的结果
success(xmlhttp);
}else{
error(xmlhttp);
}
}
}
//判断是否传入超时时间
if (timeout) {
timer = setInterval(function(){
xmlhttp.abort();//终止请求
clearInterval(timer);//清除定时器
},timeout);
}
}
测试:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>perspective</title>
<script type="text/javascript" src = "js/ajax.js"></script>
<script type="text/javascript">
window.onload = function(){
var btn = document.querySelector("button");
btn.onclick = function(){
ajax("GET","index.php",{
"username":"aa",//将要传给服务器的参数放在json对象中
"pwd":"123"
},3000//最长响应时间(等待远程服务器时间)
},function(xhr){
alert(xhr.responseText);
},function(xhr){
alert("请求失败.");
})
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
index.php
获取数据
<?php
sleep(5);//判断请求超时
echo $_GET["username"];
echo $_GET["pwd"];
?>