Java练习AJAX输入提示框
提示前:
提示后:
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。AJAX 不是新的编程语言,而是一种使用现有标准的新方法。AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。AJAX 的核心是 XMLHttpRequest 对象。就是通过这个对象结合 JS 改变网页而不重新加载。
提示框的实现方法就是通过 AJAX 创建了一个 XMLHttpRequest 对象,根据输入框的输入向服务端发送请求:
var content = document.getElementById("keyword");
if(content.value=="") {
clearContent();
return;
}
xmlHttp = newAjax();
if(xmlHttp==null) {
clearContent();
return;
}
var url = "search?keyword="+escape(content.value);
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
得到响应,进行解析,更改 DOM。
后台得到请求,解析关键字后,返回响应 json。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String keyword = request.getParameter("keyword");
List<String> listData = getData(keyword);
System.out.println(listData);
response.getWriter().write(JSONArray.fromObject(listData).toString());
}
源码:
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
<style type="text/css">
#mydiv{
position:absolute;
left:50%;
top:50%;
margin-left:-200px;
margin-top:-50px;
}
.mouseOver{
background:#708090;
color:#fffafa;
}
.mouseOut{
background:#fffafa;
color:#000000;
}
</style>
<script>
var xmlHttp;
function getMoreContents() {
var content = document.getElementById("keyword");
if(content.value=="") {
clearContent();
return;
}
xmlHttp = newAjax();
if(xmlHttp==null) {
clearContent();
return;
}
var url = "search?keyword="+escape(content.value);
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
}
function newAjax() {
try {return new XMLHttpRequest();} catch (e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e){}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e){}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e){}
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e){}
return null;
}
function callback() {
if(xmlHttp.readyState==4) {
if(xmlHttp.status==200) {
var result = xmlHttp.responseText;
var json=eval("("+result+")");
console.log(json);
setContent(json);
}
}
}
function setContent(contents) {
clearContent();
setLocation();
var size = contents.length;
console.log("haha"+size);
for(var i=0;i<size;i++) {
var nextNode = contents[i];
console.log(nextNode);
var tr = document.createElement("tr");
var td = document.createElement("td");
td.setAttribute("border",0);
td.setAttribute("bgcolor","#fffafa");
td.setAttribute("size","50");
td.onmouseover = function () {
this.className = 'mouseOver';
}
td.onmouseout=function(){
this.className='mouseOut';
};
td.onmousedown=function () {
document.getElementById("keyword").value = this.innerHTML;
}
var text = document.createTextNode(nextNode);
td.appendChild(text);
tr.appendChild(td);
document.getElementById("content_table_body").appendChild(tr);
}
}
function clearContent() {
var contentTableBody = document.getElementById("content_table_body");
//获取tr长度
var size = contentTableBody.childNodes.length;
//从后向前清除tr
for (var i = size - 1; i >= 0; i--) {
contentTableBody.removeChild(contentTableBody.childNodes[i]);
}
document.getElementById("popDiv").style.border = "";
}
//失去焦点,清除关联数据
function keywordBlur(){
clearContent();
}
//获得焦点,获取关联数据
function keywordFocus(){
getMoreContents();
}
function setLocation() {
var content = document.getElementById("keyword");
var width = content.offsetWidth-2;
var left = content["offsetLeft"]; //距左边框的距离
var top = content["offsetTop"]+content.offsetHeight; //到顶部的距离
var popDiv = document.getElementById("popDiv");
popDiv.style.border = "black 1px solid";
popDiv.style.left = left + "px";
popDiv.style.top = top + "px";
popDiv.style.width = width + "px";
document.getElementById("content_table").width = width + "px";
}
</script>
</head>
<body>
<div>
<%-- on blur在失去焦点时发生--%>
<input type="text" size="50" id="keyword" onkeyup="getMoreContents()" onblur="keywordBlur()"
onfocus="keywordFocus()">
<input type="button" value="search" width="50px">
</div>
<div id="popDiv" style="position: absolute;
z-index: 989;">
<table id="content_table" bgcolor="#ffe4c4" border="0" cellspacing="0" cellpadding="0">
<tbody id="content_table_body">
</tbody>
</table>
</div>
<div>HI</div>
</body>
</html>
java
代码:
package com.lhq.javaweblhq;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import net.sf.json.JSONArray;
@WebServlet(name = "search", value = "/search")
public class HelloServlet extends HttpServlet {
static List<String> datas = new ArrayList<>();
static {
datas.add("di");
datas.add("lhq");
datas.add("yadi");
datas.add("leiyadi");
datas.add("zhuzhu");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String keyword = request.getParameter("keyword");
List<String> listData = getData(keyword);
System.out.println(listData);
response.getWriter().write(JSONArray.fromObject(listData).toString());
}
private List<String> getData(String keyword){
List<String> list = new ArrayList<String>();
for(String data : datas){
if(data.contains(keyword)){
list.add(data);
}
}
return list;
}
public void destroy() {
}
}
pom
需要配置maven,json库,也记录一下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lhq</groupId>
<artifactId>javaweblhq</artifactId>
<version>1.0-SNAPSHOT</version>
<name>javaweblhq</name>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.7.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!--Json array start -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
右键项目 maven 创建镜像源配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>https://maven.aliyun.com/nexus/content/groups/public/</url>
</mirror>
<mirror>
<id>nexus-public-snapshots</id>
<mirrorOf>public-snapshots</mirrorOf>
<url>https://maven.aliyun.com/nexus/content/repositories/snapshots/</url>
</mirror>
</mirrors>
</settings>
参考: