欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

原生态ajax请求怎么写

程序员文章站 2022-06-10 17:22:27
...
    //第一步:创建XMLHttpRequest对象
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
   
    //第二步:设置回调函数
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    }
   
    //第三步:打开连接
    xmlhttp.open("GET","test1.txt",true);
   
    //第四步:发送请求
    //post请求的时候,需要设置requestHearder属性。两个参数,第一个参数表示头名称,第二个表示头的值
    //xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    //然后再send中传入请求的参数。如:"fname=Bill&lname=Gates"
    xmlhttp.send();