零基础学习AJAX之AJAX的简介和基础(4)


<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 = "1-3.aspx?";
                queryString += createQueryString() + "&timestamp=" + new Date().getTime();
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("GET", queryString);
                xmlHttp.send(null);
            }
            function doRequestUsingPOST() {
                createXMLHttpRequest();
                var url = "1-3.aspx?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); //解码
                }
            }
        </script>
        <form>
            <input type="text" />
            <br>
            <input type="text" />
        </form>
        <form>
            <input type="button" value="GET" />
            <br>
            <input type="button" value="POST" />
        </form>
        <div></div>


服务器端主要是根据用户输入以及请求的类型返回不同的字符串

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfypdj.html