首页 > 编程 > Java > 正文

AJAX Servlet实现数据异步交互的方法

2019-11-26 11:54:33
字体:
来源:转载
供稿:网友

在慕课网上看了AJAX的一些教程,自己参考着实现一下!

首先,导入json所需要的6个包

下载链接:JSONObjectjar_jb51.rar

总的目录:

前端页面:

首先是一个输入框:

<input type="text" id="keyword" name="keyword" onkeyup="getContents()">

onkeyup表示按下键盘时的操作

javascript:

<script type="text/javascript">    //全局xmlHttp对象  var xmlHttp;  //获得xmlHttp对象  function createXMLHttp() {    //对于大多数浏览器适用    var xmlHttp;    if (window.XMLHttpRequest) {      xmlHttp = new XMLHttpRequest();    }    //考虑浏览器的兼容性    if (window.ActiveXObject) {      xmlHttp = new ActiveXOject("Microsoft.XMLHTTP");      if (!xmlHttp) {        xmlHttp = new ActiveXOject("Msxml2.XMLHTTP");      }    }    return xmlHttp;  }    //回调函数  function callback() {    //4代表完成    if(xmlHttp.readyState == 4){      //200代表服务器响应成功,404代表资源未找到,500服务器内部错误      if(xmlHttp.status == 200){        //交互成功获得响应的数据,是文本格式        var result = xmlHttp.responseText;        //解析获得的数据        var json = eval("("+ result +")");        //获得数据之后,就可以动态的显示数据了,把数据显示到输入框下面        alert(json);      }    }  }    //获得输入框的内容  function getContents(){    //首先获得用户的输入内容,这里获得的是一个结点    var content = document.getElementById("keyword");    if(content.value ==""){      return;    }        //向服务器发送内容,用到XmlHttp对象    xmlHttp = createXMLHttp();    //给服务器发送数据,escape()不加中文会有问题    var url = "search?keyword=" + escape(content.value);    //true表示js的脚本会在send()方法之后继续执行而不会等待来自服务器的响应    xmlHttp.open("GET",url,true);    //xmlHttp绑定回调方法,这个方法会在xmlHttp状态改变的时候调用,xmlHttp状态有0-4,    //我们只关心4,4表示完成    xmlHttp.onreadystatechange=callback;    xmlHttp.send(null);  }</script>

总的index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript">    //全局xmlHttp对象  var xmlHttp;  //获得xmlHttp对象  function createXMLHttp() {    //对于大多数浏览器适用    var xmlHttp;    if (window.XMLHttpRequest) {      xmlHttp = new XMLHttpRequest();    }    //考虑浏览器的兼容性    if (window.ActiveXObject) {      xmlHttp = new ActiveXOject("Microsoft.XMLHTTP");      if (!xmlHttp) {        xmlHttp = new ActiveXOject("Msxml2.XMLHTTP");      }    }    return xmlHttp;  }    //回调函数  function callback() {    //4代表完成    if(xmlHttp.readyState == 4){      //200代表服务器响应成功,404代表资源未找到,500服务器内部错误      if(xmlHttp.status == 200){        //交互成功获得响应的数据,是文本格式        var result = xmlHttp.responseText;        //解析获得的数据        var json = eval("("+ result +")");        //获得数据之后,就可以动态的显示数据了,把数据显示到输入框下面        alert(json);      }    }  }    //获得输入框的内容  function getContents(){    //首先获得用户的输入内容,这里获得的是一个结点    var content = document.getElementById("keyword");    if(content.value ==""){      return;    }        //向服务器发送内容,用到XmlHttp对象    xmlHttp = createXMLHttp();    //给服务器发送数据,escape()不加中文会有问题    var url = "search?keyword=" + escape(content.value);    //true表示js的脚本会在send()方法之后继续执行而不会等待来自服务器的响应    xmlHttp.open("GET",url,true);    //xmlHttp绑定回调方法,这个方法会在xmlHttp状态改变的时候调用,xmlHttp状态有0-4,    //我们只关心4,4表示完成    xmlHttp.onreadystatechange=callback;    xmlHttp.send(null);  }</script></head><body>  <input type="text" id="keyword" name="keyword" onkeyup="getContents()"></body></html>

后端:

AjaxServlet.java

package com.loger.servlet;import java.io.IOException;import java.util.ArrayList;import java.util.List;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 net.sf.json.JSONArray;/** * Servlet implementation class AjaxServlet */@WebServlet("/search")public class AjaxServlet extends HttpServlet {  private static final long serialVersionUID = 1L;    static List<String> list = new ArrayList<>();  static{    list.add("chenle");    list.add("陈乐");  }      /**   * @see HttpServlet#HttpServlet()   */  public AjaxServlet() {    super();    // TODO Auto-generated constructor stub  }  /**   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)   */  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    //设置编码    request.setCharacterEncoding("utf-8");    response.setCharacterEncoding("utf-8");        //首先获得客户端发送来的数据    String keyword = request.getParameter("keyword");    System.out.println(keyword);                //返回json数据    response.getWriter().write(JSONArray.fromObject(list).toString());  }  /**   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)   */  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    // TODO Auto-generated method stub  }}

运行结果:

这就是AJAX的实现步骤,其他在页面上把内容显示出来,如输入验证码时在旁边实时提示是否正确等操作,通过JS实现即可,由于本人没怎么学过js,就这样子吧!!!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表