2.Ajax的作用:可以不刷新网页,点击或者一系列动作从而更新网页内容
3.Ajax的应用场景:页面上拉下拉加载更多(新浪网下拉刷新数据),注册登录验证(163邮箱注册),搜索框提示下拉框(百度下拉框)
4.Ajax在JavaScript创建
<script>
//创建Ajax实例
var xhr = new XMLHttpRequest()
//设置请求行open()
xhr.open("get", "URL以及需要传递的参数数据")
//发送请求
xhr.send(传递参数)
//通过onload事件接收Ajax值
xhr.onload = function() {
console.log(xhr.responseText); //接收Ajax值
};
</script>
<script>
//创建Ajax实例
var xhr = new XMLHttpRequest()
//发送get请求 ,请求地址是http://127.0.0.1/
xhr.open("get", "http://127.0.0.1/?age=10")
//发送请求
xhr.send(null)
//通过onload事件接收Ajax值
xhr.onload = function() {
console.log(xhr.responseText); //接收Ajax值
};
</script>
<script>
//数据
var str = 'name=张三&age=18';
//创建Ajax实例
var xhr = new XMLHttpRequest()
//发送get请求 ,请求地址是http://127.0.0.1/
xhr.open("post", "http://127.0.0.1/")
//设置响应头
xhr.setRequestHeader('Content-Type', 'application/x-www-from-urlencoded');
//发送post数据
xhr.send(str)
//通过onload事件接收Ajax值
xhr.onload = function() {
console.log(xhr.responseText); //接收Ajax值
};
</script>
<script>
//数据
var str = {
"name": "张三",
"age": "18"
};
//创建Ajax实例
var xhr = new XMLHttpRequest()
//发送get请求 ,请求地址是http://127.0.0.1/
xhr.open("post", "http://127.0.0.1/")
//设置响应头
xhr.setRequestHeader('Content-Type', 'application/json');
//发送post数据
xhr.send(JSON.stringify(str)) // JSON.stringify转换成json字符串
//通过onload事件接收Ajax值
xhr.onload = function() {
console.log(JSON.parse(xhr.responseText)); //接收Ajax值
};
</script>
8.通过ajax状态码接收值
<script>
//数据
var str = {
"name": "张三",
"age": "18"
};
//创建Ajax实例
var xhr = new XMLHttpRequest()
//发送get请求 ,请求地址是http://127.0.0.1/
xhr.open("post", "http://127.0.0.1/")
//设置响应头
xhr.setRequestHeader('Content-Type', 'application/json');
//发送post数据
xhr.send(JSON.stringify(str)) // JSON.stringify转换成json字符串
//通过onload事件接收Ajax值
// xhr.onload = function() {
// console.log(JSON.parse(xhr.responseText)); //接收Ajax值
// };
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
//ajax状态码等于4 和 浏览器状态码等于200
console.log(JSON.parse(xhr.responseText));
}
}
</script>
总结 : 在javascript中 创建ajax 请求只需要四步骤 但post传值需要设置响应头
注意事项:
1. post传值只能发送 字符串类型数据 需要通过 json.staingify() 进行转换成json字符串
2. post接收值也只能接收字符串类型 需要通过 json.parse() 进行转换成json格式
3. get传值是通过地址传值的,所以传值的内容也只能通过地址发送
4. post传值默认是通过表单传值的,在ajax中传值,需要填写在 send() 中
发表评论