ajax基础使用的四个步骤
四个步骤
1创建对象 let xhr = new XMLHttpRequest();
2建立连接xhr=open()
3发送请求 xhr=send()是发送的意思
4接受结果 xhr.onreadystatechange 获取响应数据 responseText
使用的实例
<body>
<input type="text" >
<button>查询天气</button>
<script>
document.querySelector('button').onclick = function(){
// 获取到城市名称
let city = document.querySelector('input').value;
// 1、创建对象 XMLHttpRequest是内置的对象
let xhr = new XMLHttpRequest;
// 2、建立连接
// xhr.open(method,url,async)
// method 表示请求方式 对应的表示数据操作方式 数据操作就是增(post)删(delete)改(put)查(get) get与delete类似 post与put类似 请求方式属于http协议中所约束的方式 最常用的是上面四种
// url 表示请求地址
// async表示是否异步 默认true 就是异步 一般不传递第三个参数
xhr.open('get','https://v0.yiketianqi.com/api?unescape=1&version=v61&appid=71362535&appsecret=eWd88Bnc&city='+city);
// 3、发送请求 send方法可以传递字符串表示请求过程中携带的数据 例如 查询的城市,例如邮箱是什么 但是一般 get delete请求参数在url地址上 post请求与put请求参数才在send方法中
xhr.send();
// 4、接受结果
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
// 大多数得到的都是JSON格式的字符串 需要自己转换
console.log(xhr.responseText)
console.log(JSON.parse(xhr.responseText))
}
}
}
// console.log(JSON.parse('{a}'))
</script>
</body>