javascript写ajax

<script>
	function CreateXmlHttp() {
		var xhrobj = false;
		try {
			xhrobj = new ActiveXObject("Msxml2.XMLHTTP"); //ie msxml3.0+
		}catch (e) {
            try {
                xhrobj = new ActiveXObject("Microsoft.XMLHTTP"); //ie msxml 2.6
            } catch (e2) {
                xhrobj = false;
            }
        }
        if (!xhrobj && typeof XMLHttpRequest != 'undefined') { //firefox opera 8.0 safari
            xhrobj = new XMLHttpRequest();
        }
        return xhrobj;
    }
    var xhr = CreateXmlHttp();
    window.onload = function() {
       Get();
  	}
	function Get() {
		//1、设置请求方式、目标、是否异步
		//1.1 Get方式
		xhr.open("GET", "http://192.168.1.107:8080/home.json", true);
		//===============如果是Post方式,请按下面的进行设置====================
		//1.2 Post方式,如果是Post方式,还需要其他一些设置
		xhr.open("POST", "http://192.168.1.107:8080/home.json", true);
		//1.2.1设置HTTP的输出内容类型为:application/x-www-form-urlencoded
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		//1.2.2设置浏览器不使用缓存,服务器不从缓存中找,重新执行代码,而且服务器返回给浏览器的时候,告诉浏览器也不要保存缓存。
		xhr.setRequestHeader("If-Modified-Since", "0");

		//2、设置回调函数
		xhr.onreadystatechange = wacthing;  //wacthing是方法名

		//3、发送请求
		xhr.send(null); //GET方式
		xhr.send(""); //POST方式
	}

	 //回调函数
	 function wacthing() {
	    if (xhr.readyState == 4) {
	        if (xhr.status == 200) {
	            var res = xhr.reponseText; //获得服务器返回的字符串
	            alert(res)
	        }
	    }
	}
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值