使用ajax异步传值生成首字母索引大致有以下几个步骤:
1、服务器端使用servlet提取出数据库里的数据;
2、使用首字母工具类对数据进处理得到首字母;
3、再将首字母和数据一一对应存入json数组,并返回到客户端;
4、HBuilder中的html文件使用ajax接受传值并动态添加数据显示。
四点详细阐释如下:
1、用servlet提取数据库的数据应该不是什么问题,sql server、mysql等之类的数据库语句都是通用的,只是驱动和使用的jar包有所不同。
public List<baike> loadAll() throws SQLException
{
List<baike> list=new ArrayList<>();
Connection connection=null;
connection = GBUtil.get();
Statement stmt=connection.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM HotWord");
String name;
String content;
String type;
String num;
while(rs.next())
{
name=rs.getString("name").trim();
content=rs.getString("content").trim();
type=rs.getString("type").trim();
num=rs.getString("num").trim();
baike baike=new baike();
baike.setName(name);
baike.setContent(content);
baike.setType(type);
baike.setNum(num);
list.add(baike);
}
stmt.close();
connection.close();
return list;
}
在自定义的类里自定义一个调取全部数据的方法,来打包成一个集合,方便在servlet里调用。
2、对数据进行处理得到首字母:
首字母工具类(HeadUtil.java):
package com.gb.util;
import java.util.Random;
public class HeadUtil
{
public static String getPYIndexStr(String strChinese, boolean bUpCase)
{
try
{
StringBuffer buffer = new StringBuffer();
byte b[] = strChinese.getBytes("GBK");//把中文转化成byte数组
for(int i = 0; i < b.length; i++){
if((b[i] & 255) > 128)
{
int char1 = b[i++] & 255;
char1 <<= 8;
int chart = char1 + (b[i] & 255);
buffer.append(getPYIndexChar((char)chart, bUpCase));
continue;
}
char c = (char)b[i];
if(!Character.isJavaIdentifierPart(c))
c = 'A';
buffer.append(c);
}
return buffer.toString().toUpperCase();
}
catch(Exception e)
{
System.out.println((new StringBuilder()).append("\u53D6\u4E2D\u6587\u62FC\u97F3\u6709\u9519").append(e.getMessage()).toString()); }
return null;
}
private static char getPYIndexChar(char strChinese, boolean bUpCase){
int charGBK = strChinese;
char result;
if(charGBK >= 45217 && charGBK <= 45252)
result = 'A';
else
if(charGBK >= 45253 && charGBK <= 45760)
result = 'B';
else
if(charGBK >= 45761 && charGBK <= 46317)
result = 'C';
else
if(charGBK >= 46318 && charGBK <= 46825)
result = 'D';
else
if(charGBK >= 46826 && charGBK <= 47009)
result = 'E';
else
if(charGBK >= 47010 && charGBK <= 47296)
result = 'F';
else
if(charGBK >= 47297 && charGBK <= 47613)
result = 'G';
else
if(charGBK >= 47614 && charGBK <= 48118)
result = 'H';
else
if(charGBK >= 48119 && charGBK <= 49061)
result = 'J';
else
if(charGBK >= 49062 && charGBK <= 49323)
result = 'K';
else
if(charGBK >= 49324 && charGBK <= 49895)
result = 'L';
else
if(charGBK >= 49896 && charGBK <= 50370)
result = 'M';
else
if(charGBK >= 50371 && charGBK <= 50613)
result = 'N';
else
if(charGBK >= 50614 && charGBK <= 50621)
result = 'O';
else
if(charGBK >= 50622 && charGBK <= 50905)
result = 'P';
else
if(charGBK >= 50906 && charGBK <= 51386)
result = 'Q';
else
if(charGBK >= 51387 && charGBK <= 51445)
result = 'R';
else
if(charGBK >= 51446 && charGBK <= 52217)
result = 'S';
else
if(charGBK >= 52218 && charGBK <= 52697)
result = 'T';
else
if(charGBK >= 52698 && charGBK <= 52979)
result = 'W';
else
if(charGBK >= 52980 && charGBK <= 53688)
result = 'X';
else
if(charGBK >= 53689 && charGBK <= 54480)
result = 'Y';
else
if(charGBK >= 54481 && charGBK <= 55289)
result = 'Z';
else
result = (char)(65 + (new Random()).nextInt(25));
if(!bUpCase)
result = Character.toLowerCase(result);
return result;
}
}
HeadUtil这个类里面的这个getPYIndexStr方法就是用来得到首字母的,不过如果是英文开头的话就是首字母,词语的话是每个汉字的首字母,就用到servlet里后续的截取字符串了。
3、首字母的servlet如下,已经对关键步骤进行了注释:
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
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 com.gb.util.HeadUtil;
import com.alibaba.fastjson.JSONObject;
import com.gb.model.baike;
import com.gb.util.CheckIfExists;
@WebServlet("/shouzimuservlet")
public class shouzimuservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public shouzimuservlet()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//添加允许跨域访问语句
response.setHeader("Access-Control-Allow-Origin", "*");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
//得到客户端传来的数据,判断确认是首字母索引,继续进行操作
String method = request.getParameter("method");
System.out.println("method");
if(method.equals("shouzimu"))
{
//引入包含调取数据库数据的方法的类
CheckIfExists checkIfExists=new CheckIfExists();
//jsonObject
//初始化
JSONObject json = new JSONObject();
List<JSONObject> jsons = new ArrayList<>();
List<baike> list=new ArrayList<>();
try
{
//调取全部数据
list=checkIfExists.loadAll();
}
catch (Exception e)
{
e.printStackTrace();
}
String string;
String str;
JSONObject json1=null;
//循环遍历,对取得数据集合中的每个数据进行操作
for(baike baike:list)
{
//定义字符串为该对象名称
string= baike.getName();
//调用HeadUtil工具类中的方法调取名称的首字母(这样取得的是每个字的首字母,例如:字母,得到的就是ZM)
string=HeadUtil.getPYIndexStr(string,true);
//字符串截取得到第一个即为首字母
str=string.substring(0, 1);
json1 = new JSONObject();
//向json中放入数据
json1.put("zimu",str);
json1.put("name",baike.getName());
//向json数组中放入json对象
jsons.add(json1);
System.out.println(json1.get("zimu"));
System.out.println(json1.get("name"));
}
System.out.println(jsons);
response.setCharacterEncoding("utf-8");
//输出数据
response.getWriter().write(jsons.toString());
}
}
}
4、客户端的html文件书写:
我在html书写时使用了较为便捷的layui框架,因为HBuilder这种html转安卓App的开发,html要做到自适应这一点。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="../css/mui.min.css">
<!--App自定义的css-->
<link rel="stylesheet" type="text/css" href="../css/app.css"/>
<link rel="stylesheet" href="../assets/css/layui.css">
<link rel="stylesheet" href="../assets/css/admin.css">
</head>
<body onload="init()"> <!-- body里的onload方法,开局引用init() -->
<!-- 写好A~Z 26个下拉菜单的第一层,内层使用ajax动态添加--> <button class="layui-btn layui-btn-normal" style="width:100%">首字母分类</button>
<div class="layui-collapse" lay-accordion="">
<div class="layui-colla-item">
<h2 class="layui-colla-title">A<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content layui-show" id="inside1"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">B<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside2"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">C<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside3"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">D<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside4"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">E<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside5"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">F<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside6"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">G<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside7"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">H<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside8"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">I<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside9"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">J<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside10"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">K<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside11"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">L<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside12"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">M<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside13"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">N<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside14"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">O<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside15"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">P<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside16"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">Q<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside17"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">R<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside18"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">S<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside19"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">T<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside20"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">U<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside21"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">V<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside22"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">W<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside23"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">X<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside24"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">Y<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside25"> </div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">Z<i class="layui-icon layui-colla-icon"></i></h2>
<div class="layui-colla-content" id="inside26"> </div>
</div>
</div>
</body>
</html>
<script src="../assets/layui.all.js"></script>
<script src="../js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function init()
{
$.ajax
({
type:'GET',
url:'http://服务器的ip地址:端口号/HotWord1/shouzimuservlet',//服务器的servlet地址
data:
{
method:'shouzimu'//对应服务器端method接受的发送请求
},
success:function(data)
{
var j;
//循环遍历
for(j=65;j<91;j++)//65~91是阿斯卡码表里A~Z,在下面就把这些数变成字母来进行和数据首字母的比对
{
var str=String.fromCharCode(j);//将循环的数据变成字符
var inside = document.getElementById('inside'+(j-64)); //获取页面写好的标签
var html = '';
var i;
for(i=0;i<data.length;i++)
{
if(str==data[i].zimu)//如果数据的首字母和当前字母一样,用html动态添加
{
//定义html
html += '<p><a href="https://baike.baidu.com/item/'+data[i].name+'">'+data[i].name+'</a></p><hr />'; } }
inside.innerHTML = html;//添加显示
}
},
error:function(error)
{
console.log('出现错误!')//
},
dataType:'json'//数据类型为json
});
}
</script>
大概就是如下效果了:
问题及解决:
1、问题:例如数据里马云、马化腾,都是首字母M开头,最开始在显示时出现了动态添加替换,就是先是动态添加了马云,之后马化腾替换掉了马云,每个首字母下只有一个数据。
2、解决:在对动态添加这部分代码进行循环的修改和内外层循环调整之后,问题得到了解决。