// 1.创建小黄人对象(哈哈其实就是xhr)
var xhr = new XMLHttpRequest()
// 2.绑定事件监听函数
xhr.onreadystatechange = function(){
//readyState 属性存有 xhr 的状态信息, 为4时: 请求已完成,且响应已就绪
if(xhr.readyState==4){
// 5.拿数据 , 200表示异步调用成功
if(xhr.status==200){
console.log(xhr.responseText)
}
}
}
// 3.建立连接
xhr.open("GET","http://47.95.123.51:8080/tjj/tjj/app-live-type-statistics/mylist")
// 4.发送请求
xhr.send()
兄弟,相信你已经看懂了,不会继续康康,接下来我们来点实用的。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
// 1.创建小黄人对象
// 老铁这次写的谨慎一点
var xhr = null;
// 首先判断有没有小黄人对象,有朋友肯定想怎么能没有,哈哈以前还真有可恶的,比如老鼠屎ie6
if (window.XMLHttpRequest) {
//如果不考虑ie的老版本就不用写判断了
xhr = new XMLHttpRequest();
} else {
//老版本的IE,ie6及以下(老鼠屎)
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
// 2.绑定事件监听函数
xhr.onreadystatechange = function() {
//readyState 属性存有 xhr 的状态信息, 为4时: 请求已完成,且响应已就绪。
// 那1,2,3呢都是干啥的.去菜鸟里面慢慢看
if (xhr.readyState === 4) { //是否准备就绪
// http请求
// 1xx 信息类
// 2xx 表示成功 200
// 3xx 重定向 304
// 4xx 客户端错误 404
// 5xx 服务端错误
// 5.拿数据
if (xhr.status === 200) { //是否为成功的响应
console.log(xhr.responseText);
} else {
console.log('接收到一个非成功的ajax响应' + xhr.status);
}
}
}
// 3.建立连接
// xhr.open(请求方式,请求地址,[bool])true表示异步,false表示同步,true表示默认
// GET方式 "地址?参数名="+参数值(变量)
var provice = "陕西";
xhr.open("GET","https://tianqiapi.com/api?version=v71&appid=24745176&appsecret=4KTAvQuL&province="+provice,true)
// 3.1使用post发送之前必须设置请求头
// xhr.open("POST","xxx.php")
// xhr.setRequestHeader("Content-type","application/json; charset=utf-8"); json
// xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); 表单数据
// xhr.setRequestHeader("Content-type", "text/plain; charset=utf-8"); 纯文本
// xhr.setRequestHeader("Content-type", "text/html; charset=utf-8"); HTML
// 4.发送消息请求
// xhr.send(发送的参数)
xhr.send(null);
// 4.1使用post方式时
// xhr.send("name="+unameval)
</script>
</html>