let xhr = new XMLHttpRequest();
open
功能:设置传参类型,请求地址和参数
参数:open(请求类型,url?参数,是否异步)
xhr.open("get","1xhrProperty.txt",true);
send
功能:对get传参而言,只是发送参数功能,无参
对post传参,需要传递参数,有参
xhr.send();
onreadystatechange:该事件是由readystate状态码发生改变而被触发
readyState2,3,4都会触发onreadystatechange
readyState:xhr对象的状态码
0:刚创建完对象后
1:open方法调用结束
2:send方法调用,请求发送出去
3:请求已经发送至服务器
4:服务器接收请求且完成解析,准备返回
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
status:http协议的状态码
200通讯成功
404网址写错
500服务器问题
if(xhr.readyState == 4 && xhr.status == 200){
//responseText:服务器返回给前端的信息
console.log(xhr.responseText);
}
}
ajaxpost
1.设置请求头,将参数以form表单post的方式发送
2.参数在send中传递
key1=value1&key2=value2...
xhr.open("post","2ajaxPost.php",true);
//1.设置请求头,将参数以form表单post的方式发送
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//2.参数在send中传递
//key1=value1&key2=value2...
xhr.send("userName="+this.value);
接口:与后端交互的标准
url:请求地址
参数:请求参数
返回数据:数据格式
返回json对象的两种方法
1.返回json字符串
2.通用php返回json数组
<script type="text/javascript">
let xhr = new XMLHttpRequest();
xhr.open("get","1ajaxReturnJson.php",true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
fun(xhr.responseText);
}
}
function fun(resText){
let json = JSON.parse(resText);
for(let index in json){
console.log(json[index]);
}
}
</script>
<?php
header("Content-type:text/html;charset=utf-8");
echo '{"name":"小七","age":18}';
//2.通用php返回json数组
$arr = ["name"=>"小七","age"=>22];
//将数组转换为json字符串
echo json_encode($arr);
?>
ajaxFun
功能:发送请求,接收响应,
参数:
type:get还是post,
url:服务器地址,
isAsyn:是否异步,
data:key1=value1&key2=value2,
callBack:用来接收responseText
function ajax(type,url,isAsyn,data,callBack){
let xhr = new XMLHttpRequest();
type = type.toLowerCase();
if(type == "get"){
let urlParams = url;
if(data != ""){
urlParams += "?" + data;
}
xhr.open(type,urlParams,isAsyn);
xhr.send();
}else if(type == "post"){
xhr.open(type,url,isAsyn);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(data);
}else{
console.log("type参数错误");
}
xhr.onreadystatechange = function(){
if(xhr.status==200 && xhr.readyState==4){
callBack(xhr.responseText);
}
}
}
ajax("GET","6ajaxFun.php",true,"name=laowang&pwd=666",fun);
ajax("post","6ajaxFun.php",true,"name=高少鑫&pwd=999",fun);
function fun(resText){
console.log(resText);
}
<?php
header("Content-type:text/html;charset=utf-8");
$name = $_REQUEST["name"];
$pwd = $_REQUEST["pwd"];
echo $name." ".$pwd;
?>
Promise
Promise作用:
解决回调地狱问题,将函数的嵌套调用变为平级调用,(改变回调函数传参的方式)
f1().then(f2).then(f3).then(f4);
Promise语法:
1.promise对象通常放入一个函数体内
2.promise会作为该函数的返回值
3.在该函数调用结束后,通过then方法传入回调函数
function fun(){
let p = new Promise(function(f1,f2){
f2();
});
return p;
}
function f1(){
console.log("heihei");
}
function f2(){
console.log("haha");
}
fun().then(f1,f2);