异步交互(一)

前言:

        本文为javascript中ajax使用的快速指南,旨在作为一个快速上手使用的资料备份,更长使用的为jQuery中封装后的ajax技术。


一、获取XMLHttpRequest对象

        ajax的核心为XMLHttpRequest对象,通过该对象和服务器进行异步交互,因此使用Ajax技术的第一步,就是从不同的浏览器获取该对象的实例。

获取xhr对象的代码(附注:该段代码源自w3cschool):

function getXmlHttpRequest() {
	var xmlHttp = null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}


二、发送异步请求

        常用的web请求方式有两种,即get和post,得到xhr对象之后,通过这两种请求方式可以和服务器进行异步交互。

        get方式:get方式与服务器进行交互,无需显示传递参数,传递的参数附在url末尾,因此获取xhr对象之后,send方法传入的参数为null;

        post方式:post方式与服务器进行交互,请求参数封装在请求体中,因此需要通过xhr的send方法显示传递参数,另外,post方式交互原理是通过xhr模拟post方式提交表单,因此必须显示的设置请求头参数"content-type"为"application/x-www-form-urlencoded",否则服务器不能正常解析请求(具体原因,请参考HTTP协议);

        javascript实现的代码如下:

window.onload = function(){
			var xhr = getXmlHttpRequest();
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4)
					if(xhr.status == 200){
						alert("数据已经成功发送到服务器");
						alert(xhr.statusText);
					}
			};
			
			//get方式
			document.getElementById("getBtn").onclick = function(){
				xhr.open("get", "/ajax_demo/info?username=zhangsan&password=123");
				xhr.send(null);
			};
			
			//post方式
			document.getElementById("postBtn").onclick = function(){
				xhr.open("post", "/ajax_demo/info");
				xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
				//post方式发送参请求参数
				xhr.send("username=lisi&password=456");
			};
			
			document.getElementById("showProductInfo").onclick = function(){
				xhr.open("post", "/ajax_demo/product");
				xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
				//post方式,如果无参,则传null
				xhr.send(null);
			};
		};

附注:

        本文如有错漏,烦请联系,不胜感激!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值