HTML文件
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset='utf-8'/>
<title>原生Ajax</title>
</head>
<body>
<button class="btn1">发送原生请求</button>
<button class="btn2">发送jqAjax请求</button>
<script src="js/jquery-1.12.3.min.js"></script>
<script>
//原生ajax请求--xmlhttprequest
document.querySelector('.btn1').onclick = function (){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (){
if(xhr.readyState == 4){
if(xhr.status == 200){
console.log(JSON.parse(xhr.responseText));
}
}
};
var formData = new FormData();
formData.append('uname','frank');
formData.append('upass','123456');
xhr.open('post', 'lesson1_reivew.php', true);
xhr.send(formData);
};
document.querySelector('.btn2').onclick = function (){
$.ajax({
type: 'post',
url: '01reivew.php',
dataType: 'json',
data: {
username:'jq-frank',
password:'jq-123456'
},
success: function (res){
console.log(res);
}
});
};
//构建自己的ajax框架,
//约定1:参数模仿jq的格式,也是一个json
// json中必要字段有:
// type请求类型、url请求地址、data请求参数、success请求回调
function frankAjax(paramsObj){
(1)先处理paramsObj参数,把这个json格式的参数转换成必要的格式
a.如果是get请求,将参数拼接到url后面
{...}->[...]->join()->url+join()
b.如果是post请求,则构建formData参数对象
formData.append(..., ...);
(2)准备xhr对象,然后实现onreadystatechange,准备发送请求
xhr.onreadystatechange = function (){...};
(3)准备open()
xhr.open(..., ..., true);
(4)准备send()
if(paramsObj.type == 'get'){ xhr.send(null); }
else if(paramsObj.type == 'post'){ xhr.send(formData); }
}
</script>
</body>
</html>
php文件
<?php
$success = array('msg' => 'OK', 'info' => $_POST);
echo json_encode($success);
?>