ajax是一种异步请求技术,google的成名技术之一,用的最多的就是在后台提交请求,使页面无刷新而造成到的局部刷新
最早的原生的ajax
发送get请求
var xhr = new XMLHttpRequest();//构造ajax对象
xhr.open("GET", "/infos?name=admin", true);//打开连接
xhr.send();//发送请求
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {//4 代表服务器正确的给客户端响应,客户端也正确的收到了响应
var ret = eval("(" + xhr.responseText + ")")
console.log(ret.name);
}
}
发送post请求
var xhr = new XMLHttpRequest();
xhr.open("POST", "/infos", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//
xhr.send("name=admin123");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {//4 代表响应成功
var ret = eval("(" + xhr.responseText + ")")
console.log(ret.name);
}
}
常用的jquery的ajax
发送get请求
$.ajax({
url: "/infos1?name=admin1234", //异步请求要访问的url
type: "GET",//请求方式 可以省略 默认为GET请求
dataType: "json" //url返回值的类型
}).done(function () {//如果异步请求成功 做的操作
console.log("成功...");
}).fail(function () {//如果异步请求失败 做的操作
console.log("失败...");
});
发送post请求
$.ajax({
url: "/infos",
type: "POST",//
data: "name=admin222",//这个data是异步请求的参数 相当于在url后面写参数
dataType: "json"
}).done(function (data) {//这个data 是url返回的参数
console.log(data);
}).fail(function () {
console.log("失败...");
});
当然还有一些别版本的ajax,不过都是在参数方面进行省略、精简 ,个人觉得没那个必要 就列举出来这两种版本