js实现 post/get 请求的实现:
4步曲:
创建对象:var xhr = new XMLHttpRequest();
get请求: xhr.open("get","/ajax?username=xiaopo&password=999",true);
发送请求:xhr.send();
实现:
xhr.onreadystatechange = function () {
//readyState
// 0 没有启动
//1 初始化 open之前
//2 发送请求 send之后
//3 响应 有一部分数据接收
// 4 数据全部接收
if(xhr.readyState === 4){
if(xhr.status === 200){
alert(xhr.status);
}else{
alert(xhr.status);
alert(xhr.statusText);
}
}
}
例:
var btn = document.getElementById("btn");
btn.onclick = function () {
//创建对象
var xhr = new XMLHttpRequest();
//get请求
//method url async
xhr.open("get","/ajax?username=xiaopo&password=999",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 请求头 在open后 send前
//发送请求
xhr.send();
//post请求 必须加请求头
//xhr.open("post","/ajax",true);
//post请求 必须设置请求头
//xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//xhr.send("username=qqqq&password=88888");
xhr.onreadystatechange = function () {
//readyState
// 0 没有启动
//1 初始化 open之前
//2 发送请求 send之后
//3 响应 有一部分数据接收
// 4 数据全部接收
if(xhr.readyState === 4){
if(xhr.status === 200){
alert(xhr.status);
}else{
alert(xhr.status);
alert(xhr.statusText);
}
}
}
}
JQ的Ajax:
$("#btn").click(function () {
/*$.ajax({ 直接$.Ajax 调用Ajax方法
"method": "post", 方法
"url": "/ajax", 路径为Ajax
"data": { 内容,获取什么等信息
//js.value jq.val()
"username": $("#user").val(),
"password": $("#psd").val()
},
"success": function (data) { 如果请求成功了 执行这个
console.log("success");
console.log(data);
$("#wrap").html(data);
},
"error": function (qq) { 失败了 执行这个
console.log("error");
console.log(qq);
console.log(qq.status);
console.log(qq.statusText);
}
});*/
或者直接:
//$.get();
$.post({
"url": "/ajax",
"data": {
//js.value jq.val()
"username": $("#user").val(),
"password": $("#psd").val()
},
"success": function (data) {
console.log("success");
console.log(data);
$("#wrap").html(data);
},
"error": function (qq) {
console.log("error");
console.log(qq);
console.log(qq.status);
console.log(qq.statusText);
}
}
)