javascript写ajax

来源:互联网 发布:大数据社保行业应用 编辑:程序博客网 时间:2024/05/17 07:43
<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-urlencodedxhr.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
原创粉丝点击