纯JS异步(post和get两种方法)

本文介绍了一种使用JavaScript的Ajax技术实现GET和POST请求的方法。通过具体示例展示了如何创建XMLHttpRequest对象,构造查询字符串,并发送请求到服务器。同时,文章还包含了服务器端的简单响应处理。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> js </TITLE>


</HEAD>


<BODY>
    <script type="text/javascript">
        var xmlHttp;
        function createxmlHttpRequest()
        {
            if(window.ActiveXObject)
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            else if(window.XMLHttpRequest)
                xmlHttp = new XMLHttpRequest();
        }
        function createQueryString()
        {
            var firstName = document.getElementById("firstName").value;
            var birthday = document.getElementById("birthday").value;
            var queryString = "firstName="+firstName+"&birthday="+birthday;
            return encodeURI(encodeURI(queryString));//防止乱码
        }
        function doRequestUsingGet()
        {
            createxmlHttpRequest();
            var queryString = "ajax2.asp?";
            queryString+=createQueryString()+"&timestamp="+new Date().getTime();
            xmlHttp.open("GET",queryString);
            xmlHttp.onreadystatechange = handleStateChange;
            xmlHttp.send(null);
        }
        function doRequestUsingPost()
        {
            createxmlHttpRequest();
            var url ="ajax2.asp?timestamp="+new Date().getTime();
            var queryString = createQueryString();
            xmlHttp.open("POST",url);
            xmlHttp.onreadystatechange = handleStateChange;
            xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlHttp.send(queryString);
   
        }
        function handleStateChange()
        {
            if(xmlHttp.readyState==4 && xmlHttp.status == 200)
            {
                var responseDiv = document.getElementById("serverResponse");
                responseDiv.innerHTML=decodeURI(xmlHttp.responseText);
            }
   alert(xmlHttp.responseText);
        }
    </script>


    <form id="form1" runat="server">
        <input id="firstName" type="text" /><br />
        <input id="birthday" type="text" /><br />
        <br />
        <input id="get" type="button" value="get" onclick="doRequestUsingGet();" style="width: 64px" />
        &nbsp;
        <input id="post" type="button" value="post" onclick="doRequestUsingPost();" style="width: 75px" /><br />
        &nbsp;<div id="serverResponse">
        </div>
    </form>
</BODY>
</HTML>


ajax2.asp页面:


<%
 Response.Write("000")
%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值