ajax原生写法(学习笔记)
1.创建请求
var xhr = window.XMLHttpRequest:new XMLHttpRequest?ActiveXObject("microsoft.XMLHttp")
2.准备发送(配置参数)
xhr.open("get/post",url,true/false)
注:
1)get请求数据时,将参数写入url中,exp: "/ajax/01?username="+username
2)post请求数据时,url只写路径,不加参数
3)post请求数据时,要加请求头:xhr.setRequestHeader("content-type","application-www-form-urlencoded")
3.发送请求
xhr.send()
注:
1)post请求数据时,参数加进send()中,exp:params="username="+username+"&password="+password;xhr.send(params)
4.回掉函数
xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ console.log(xhr.responseText) } } }
注:
readyState:请求返回的数据是否可用
status:请求状态码
200---请求成功
203---已成功处理了请求,但返回了另一来源的信息
304---上次请求后,网页未被修改过
400---语法错误
404---未找到页面
500---服务器错误

浙公网安备 33010602011771号