Ajax用原生js的写法
GET请求
<script>
document.querySelector('input').onclick = function(){
//查找input标签并添加点击事件
var xhr = new XMLHttpRequest();
//创建异步对象
xhr.open('get','URL?name='+value);
//添加请求方式为get,URL为请求的地址(get请求数据写在URL后面)
xhr.onreadystatechange = function(){
//设置回调函数
if (xhr.readyState==4&&xhr.status==200) {
//readyState==4表示请求完成,数据都获取到了,status==200表示请求的页面一定存在
console.log(xhr.responseText);
//获取数据
}
}
xhr.send(null);
//请求发送主体,get请求为空或者写null
}
</script>
POST请求
<script>
document.querySelector('input').onclick = function () {
//查找input标签并添加点击事件
var xhr = new XMLHttpRequest();
//创建异步对象
xhr.open('post', 'URL');
//添加请求方式为post,URL为请求的地址
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//设置请求头(将Content-type的值设置为application/x-www-form-urlencoded才能实现提交数据)
xhr.onreadystatechange = function () {
//设置回调函数
if (xhr.readyState == 4 && xhr.status == 200) {
//readyState==4表示请求完成,数据都获取到了,status==200表示请求的页面一定存在
console.log(xhr.responseText);
//获取数据
}
}
xhr.send('name='+value);
//请求发送主体,post请求数据写在发送主体中,若无发送的数据则为null
}
</script>
注意
GET请求将发送的数据写在URL的后面且发送主体为null,POST请求将发送的数据写在请求主体中URL后面不加数据。
GET请求可以忽略请求头的设置,但POST请求必须设置请求头。
请求头中Content-type的值设置为application/x-www-form-urlencoded是参考from表单在发送POST请求时请求头中默认
Content-type的值为application/x-www-form-urlencoded且可以成功获取数据