ajax

1.什么是ajax?

是通过js已异步的形式操作json

2.ajax的步骤?

1.要有浏览器
2.创建xhr对象
3.xhr.open(请求方式,请求地址,boolean|true 异步|false 同步);
4.xhr.send();//get请求里面不许传参和post请求里面需要传参
5.xhr.onreadystatechange 监测0-1,1-2,2-3,3-4 会执行四次。
通过xhr.readyState来判断当前状态
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
6. 通过xhr.status来获取服务器返回的状态码,做相应的操作。

3.封装一个ajax兼容性方法:

<script>
			function ajaxFunc(method,url,data,callback,flag){
			var xhr = null;
			if(window.XMLHttpRequest){
				xhr = new XMLHttpRequest()
			}else{
				xhr = new ActiveXObject('Miscrosoft.XMLHttp');
			}

			if(method == 'GET'){
				xhr.open(method,url+data,flag);
				xhr.send()
			}else if(method == 'POST'){
				xhr.open(method,url,flag);
				xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
				xhr.send(data);
			}

			// xhr.open('GET','./getNews.php?username=tac&age=18',true);
			// xhr.send();
			// xhr.open('POST','./getNews.php',true);
			// xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
			// xhr.send('username=tac&age=18');

			xhr.onreadystatechange = function () {
				if(xhr.readyState == 4){
					if(xhr.status == 200){
						callback(xhr.responseText)
						// console.log(JSON.parse(xhr.responseText));
					}
				}
			}

		}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值