js中get与post实现

时间:2020-01-03 09:48:23   收藏:0   阅读:94

1、get

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript">
        function checkusername() {
            // 1.获取ajax引擎
            var xhr = getXHR();

            // 2.调用open方法准备发送
            var url = checkUsername_ajax?username=+document.getElementById(username).value;
            console.log(url);
            xhr.open(get,url,true);

            // 3.发送请求
            xhr.send();

            // 4.指定回调函数
            xhr.onreadystatechange = function () {
                // readystate是4并且status是200
                if(xhr.readyState == 4 && xhr.status == 200){
                    document.getElementById("msg").innerHTML = xhr.responseText;
                }
            };
        }
        
        function getXHR() {
            if(window.XMLHttpRequest)
            {
                return new window.XMLHttpRequest();
            } else {
                return new window.ActiveXObject("Microsoft.XMLHTTP");
            }
        }
    </script>
</head>
<body>
    <form action="" method="get">
        <input type="text" name="username" id="username" onblur="checkusername()"/><br/><div id="msg"></div>
        <input type="text" name="address"/><br/>
        <input type="submit" value="login"/><br/>
    </form>
</body>
</html>

 

2、post

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript">
        function checkusername() {
            // 1.获取ajax引擎
            var xhr = getXHR();

            // 2.调用open方法准备发送
            xhr.open(post,checkUsername_ajax,true);

            // 3.发送请求 (多个参数使用&符号连接)
            // xhr.send(‘username=‘+document.getElementById(‘username‘).value+‘&address=nj‘);
            xhr.send(username=+document.getElementById(username).value);

            // 4.指定回调函数
            xhr.onreadystatechange = function () {
                // readystate是4并且status是200
                if(xhr.readyState == 4 && xhr.status == 200){
                    document.getElementById("msg").innerHTML = xhr.responseText;
                }
            };
        }
        
        function getXHR() {
            if(window.XMLHttpRequest)
            {
                return new window.XMLHttpRequest();
            } else {
                return new window.ActiveXObject("Microsoft.XMLHTTP");
            }
        }
    </script>
</head>
<body>
    <form action="" method="get">
        <input type="text" name="username" id="username" onblur="checkusername()"/><br/><div id="msg"></div>
        <input type="text" name="address"/><br/>
        <input type="submit" value="login"/><br/>
    </form>
</body>
</html>

文中checkUsername_ajax是url地址

原文:https://www.cnblogs.com/TaoYuanJieYi/p/12143097.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!