Ajax

“AJAX即Asynchronous Javascript And XML(异步JavaScript和XML),是指一种创建交互式应用的网页开发技术.”

创建xhr对象

1
2
3
4
5
6
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{//早期的IE浏览器
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}

配置请求参数

请求行

open(method,url,async)将请求发送到服务器.

method:请求的类型;GET或POST

url:文件在服务器上的位置

async:true(异步)或false(同步)

1
xhr.open('get','test.php',true);

请求头

1
2
// 当以post形式提交表单的时候,请求头里设置
xhr.setRequestHeader('Content-Type','application/x-www/form-urlencoded');

请求主体

send(string)将请求发送到服务器.以参数string形式传参,只能用在post请求.

1
xhr.send('key=value&key=value')

get请求传参方式需将参数拼接在请求行的url中

1
open('get','test.php?key=value&key=value')

请求回调

onreadystatechange当请求被发送到服务器时,我们需要执行一些基于响应的任务.每当readyState改变时,就会触发onreadystatechange事件.readyState属性存有XMLHttpRequest的状态信息.

获取全部响应头信息

1
xhr.getAllResponseHeaders()

获取指定头信息

1
大专栏  Ajaxe>
xhr.getResponseHeader('key')

readyState

0:请求未初始化

1:服务器连接已建立

2:请求已接受

3:请求处理中

4:请求已完成,且响应已就绪

status

200:”OK”

404:未找到页面

1
2
3
4
5
6
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
var data = xhr.responseText;// JSON
// var data = xhr.responseXML
}
}

Json

1
2
// json字符串
var str = '{"key":"value","key":"value"}'

json字符串转json对象

1
var data = JSON.parse(str);

json对象转json字符串

1
var jsonStr = JSON.stringify(data);

JQuery的Ajax语法

1
2
3
4
5
6
7
8
9
10
11
$.ajax({
url:'',
type:'',
dataType:'',
data: {username:'',password:''},
success:function(data){
},error:function(){
}
})
原文地址:https://www.cnblogs.com/lijianming180/p/12239683.html