AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下更新部分数据
AJAX = 异步 JavaScript 和 XML
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
通过创建XMLHttpRequest实现ajax请求的五个步骤:
// 1.创建一个异步对象 new XMLHttpRequest()
// 2.设置请求方式和请求地址 open(method,url,true)
/*
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
*/
// 3.发送请求 send()
// 4.监听状态的变化 onreadystatechange
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
//5.判断请求是否成功。并返回请求结果 :根据状态码status判断
//6.responseText是服务器返回的结果
使用get请求:
在open的url后缀中添加要传递的数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function(){
var btn = document.querySelector('button');
btn.onclick = function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','04-ajax-get.php',true);
xmlhttp.send();
xmlhttp.onreadystatechange =function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status >= 200 && xmlhttp.status <=300 || xmlhttp.status == 304 ){
console.log('success');
}else{
console.log('failed');
}
}
}
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
使用get请求并兼容ie:
ie浏览器会默认读取缓存中的内容:
在请求的地址不变的情况下,多次对该地址发送请求,默认接收第一次请求的返回值。即如果在第一次请求之后,修改该地址中的内容,再次请求也无法获取到修改的内容
所以通过在请求地址中添加随机数等形式不读取缓存中的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function(){
var btn = document.querySelector('button');
btn.onclick = function(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();// code for IE7+, Firefox, Chrome, Opera, Safari
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
//通过给请求地址后加随机数或时间等形式,使地址改变,不读取缓存值
xmlhttp.open('GET',"05-ajax-get.txt?t="+(new Date().getTime()),true);
xmlhttp.send();
xmlhttp.onreadystatechange =function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status >= 200 && xmlhttp.status <=300 || xmlhttp.status == 304 ){
console.log(xmlhttp.responseText);
}else{
console.log(xmlhttp.responseText);
}
}
}
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
使用post请求并兼容ie:
在open()和send()中设置请求头,在send()中添加要传递的数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function(){
var btn = document.querySelector('button');
btn.onclick = function(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();// code for IE7+, Firefox, Chrome, Opera, Safari
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
//通过给请求地址后加随机数或时间等形式,使地址改变,不读取缓存值
xmlhttp.open('POST','08-ajax-post.php',true);
//设置请求头
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("userName=jiaody&userAge=23");
xmlhttp.onreadystatechange =function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status >= 200 && xmlhttp.status <=300 || xmlhttp.status == 304 ){
console.log(xmlhttp.responseText);
}else{
console.log('fail');
}
}
}
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
封装ajax方法:
function obj2str(data) {
/*
{
"userName":"lnj",
"userPwd":"123456",
"t":"3712i9471329876498132"
}
*/
data = data || {}; // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
data.t = new Date().getTime();
var res = [];
for(var key in data){
// 在URL中是不可以出现中文的, 如果出现了中文需要转码
// 可以调用encodeURIComponent方法
// URL中只可以出现字母/数字/下划线/ASCII码
res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key])); // [userName=lnj, userPwd=123456];
}
return res.join("&"); // userName=lnj&userPwd=123456
}
function ajax(option) {
// 0.将对象转换为字符串
var str = obj2str(option.data); // 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.设置请求方式和请求地址
/*
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
*/
if(option.type.toLowerCase() === "get"){
xmlhttp.open(option.type, option.url+"?"+str, true);
// 3.发送请求
xmlhttp.send();
}else{
xmlhttp.open(option.type, option.url,true);
// 注意点: 以下代码必须放到open和send之间
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(str);
}
// 4.监听状态的变化
xmlhttp.onreadystatechange = function (ev2) {
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
if(xmlhttp.readyState === 4){
clearInterval(timer);
// 判断是否请求成功
if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
xmlhttp.status === 304){
// 5.处理返回的结果
// console.log("接收到服务器返回的数据");
option.success(xmlhttp);
}else{
// console.log("没有接收到服务器返回的数据");
option.error(xmlhttp);
}
}
}
// 判断外界是否传入了超时时间
if(option.timeout){
timer = setInterval(function () {
console.log("中断请求");
xmlhttp.abort();
clearInterval(timer);
}, option.timeout);
}
}
使用封装好的ajax方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="myAjax2.js"></script>
<script>
window.onload = function(){
var btn = document.querySelector('button');
btn.onclick = function(){
ajax({
url:'08-ajax-post.php',
data:{
'userName':'jiaody',
'userAge':23
},
type:'POST',
timeout: 3000,
success:function(xhr){
console.log(xhr.responseText)
},
fail:function (xhr) {
console.log('fail')
}
})
}
}
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
jQuery中的ajax方法:
$.ajax({
url:‘请求的地址’,
type:‘get或者post’,
data:{要发送的数据},
success(msg){请求成功返回的函数},
fail(msg){请求失败}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-1.12.4.js"></script>
<script>
$(function () {
$('button').click(function(){
$.ajax({
url:'09-ajax-jquery.php',
data:{
'userName':'jiaody',
'userPwd':2333
},
type:'get',
success(msg){
console.log(msg);
},
fail(msg){
console.log(msg)
}
})
})
})
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>