一、ajax发送get请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>05-ajax-get</title>
<!--
1.什么是ajax
ajax是与服务器交换数据并更新部分网页的艺术,在不重新加载整个网页的情况下更新数据
-->
<script>
window.onload = function (ev) {
var oBtn = document.querySelector("button");
oBtn.onclick = function (ev1) {
//1.创建一个异步对象
var xmlhttp = new XMLHttpRequest();
//2.设置请求方式和请求地址
/*
* method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
* */
xmlhttp.open("GET", "05-ajax-get.php", true);
//3.发送请求
xmlhttp.send()
//4.监听状态变化
xmlhttp.onreadystatechange = function (ev2) {
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
if (xmlhttp.readyState === 4){
//判断是否请求成功,xmlhttp.status返回的http状态码
if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
xmlhttp.status ===304){
//5.处理返回结果
console.log(xmlhttp.responseText)
}
}
}
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
2.封装ajax get请求,新建myAjax.js文件
function ajax(url, obj, timeout, success, error) {
/*
* url:请求地址
* obj:请求数据对象
* timeout:请求超时时间
* success:请求成功时的回调
* error:请求失败时的回调
* */
//0.格式化obj
function obj2str(obj) {
obj.t = new Date().getTime();
var res = [];
for (var key in obj){
//encodeURIComponent()将请求中的中文进行重新编码
res.push(encodeURIComponent(key)+ "=" + encodeURIComponent(obj[key]));
}
return res.join("&")
}
//1.创建一个异步对象
var xmlhttp;
//判断浏览器是否支持XMLHttpRequest
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.设置请求方式和请求地址
/*
* method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
* */
var str = obj2str(obj)
//+ "?t=" + (new Date().getTime())兼容浏览器
xmlhttp.open("GET",url + "?" + str,true);
//3.发送请求
xmlhttp.send();
//4.监听状态变化
xmlhttp.onreadystatechange = function (ev2) {
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
if (xmlhttp.readyState === 4) {
//关闭定时器
clearInterval(timer);
//判断是否请求成功,xmlhttp.status返回的http状态码
if (xmlhttp.status >= 200 && xmlhttp.status < 300 ||
xmlhttp.status === 304) {
//5.处理返回结果
success(xmlhttp);
}else {
error(xmlhttp)
}
}
};
if (timeout){
//请求响应时间等于timeout时,中断请求,关闭定时器
timer = setInterval(function () {
console.log("中断请求");
xmlhttp.abort();
//关闭定时器
clearInterval(timer);
}, timeout);
}
}
3.调用封装的ajax get请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>06-ajax-get</title>
<script src="myAjax.js"></script>
<!--
1.什么是ajax
ajax是与服务器交换数据并更新部分网页的艺术,在不重新加载整个网页的情况下更新数据
-->
<script>
window.onload = function (ev) {
var oBtn = document.querySelector("button");
oBtn.onclick = function (ev1) {
//在URL中不可以出现中文的,如果出现中文需要调用encodeURIComponent进行转码
//url中只能出现字母、数字、下划线、ASCII码
ajax("05-ajax-get.php",
{"username":"doulihang"},
3000,
function (xhr) {
alert(xhr.responseText)
},
function (xhr) {
alert("请求失败")
}
)
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>