【Java Web基础】(十一)Ajax示例:根据用户输入的学号填充用户信息

       本例完成的任务:用户输入完学号时触发Ajax异步请求,从服务器获取学号所对应学生信息,并对页面中相应的学生信息进行更新填充。


输入信息的JSP界面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>example12_2.jsptitle>
    <script type="text/javascript" src="example12_2.js" charset="UTF-8">script>
head>
<body>
    <h1>获取学号对应的学生信息h1>
    <p>学号:<input type="text" name="sno" onblur="ajaxFunction(this.value)" />p>
    <p>姓名:<input type="text" name="sname" id="sname" readonly />p>
    <p>年龄:<input type="text" name="sage" id="sage" readonly />p>
    <p>院系:<input type="text" name="sdept" id="sdept" readonly />p>
body>
html>

对应的JS文件:example12_2.js:
function createXHR(){
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlhttp;
}
function ajaxFunction(sno) {
    xhr = createXHR();
    var url = "AjaxTestServlet?sno=" + sno;
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4 && xhr.status == 200){
            var resData = xhr.responseText.split(",");
            document.getElementById("sname").value = resData[0];
            document.getElementById("sage").value = resData[1];
            document.getElementById("sdept").value = resData[2];
        }
    };
    xhr.send();
}

Servlet文件为AjaxTestServlet.java:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/example12_2/AjaxTestServlet")
public class AjaxTestServlet extends HttpServlet {
    private static final long serialVersionUID=1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Map<String,String> stus=new HashMap<String , String>();
        stus.put("20190101","陈恒 01,77,计算机学院");
        stus.put("20190102","陈恒 02,88,软件学院");
        stus.put("20190103","陈恒 03,99,信息学院");
        String sno = request.getParameter("sno");
        String stu = stus.get(sno);
        if(stu == null){
            stu = "error,error,error";
        }
        response.getWriter().print(stu);
    }
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        doGet(request,response);
    }
}

展示效果如下:

【Java Web基础】(十一)Ajax示例:根据用户输入的学号填充用户信息_第1张图片
仅输入学号并失去焦点(因为给的条件是onblur(),失去焦点后悔触发)后:
【Java Web基础】(十一)Ajax示例:根据用户输入的学号填充用户信息_第2张图片

你可能感兴趣的:(Java,Web基础)