原生JS实现Ajax

页面代码,为了测试设置了一个发送异步请求的按钮和文本框


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script>
        function fun() {
            //发送异步请求
            //1.创建核心对象
            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");
            }

            //2.建立连接
            /*
                参数:
                    1.请求方式:GET,POST
                        get方式:请求参数在URL后拼接,send方法为无参
                        post方式:请求参数在send方法中定义
                    2.请求的URL:
                    3.同步或异步请求:true(异步)或false(同步)
             */
            xmlhttp.open("GET","ajaxServlet?username=tom",true);

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

            //4.接收并处理来自服务器的响应结果
            //获取方式 xmlhttp.responseText
            //什么时候获取?当服务器响应成功后再获取
            //当xmlhttp对象的就绪状态改变时,会触发事件onreadyStatechange

            xmlhttp.onreadystatechange=function()
            {
                //判断就绪状态是否为4,判断status响应状态码是不是200
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    //获取服务器的响应结果
                   var responseText = xmlhttp.responseText;
                   alert(responseText);
                }
            }

        }

    script>
head>
<body>
    <input type="button" value="发送异步请求" onclick="fun();"/>
    <input type="text"/>
body>
html>

后台代码

@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数
        String username = request.getParameter("username");
        System.out.println(username);//tom

        //2.响应
        response.getWriter().write("hello:" + username);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

直接点击按钮,即发送异步请求

原生JS实现Ajax_第1张图片

你可能感兴趣的:(ajax,ajax,js,java)