标签:rac test $.ajax nal servlet net cti erp ram
1、index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link type="text/css" href="css/jquery-ui-1.10.4.custom.css" rel="stylesheet" /> <script src="js/jquery-1.10.2.js"></script> <script src="js/jquery-ui-1.10.4.custom.js"></script> <script type="text/javascript" > $(function(){ //自动补全 $("#username").autocomplete({ minLength:1, source: function(request,response){ $.ajax({ url: ‘Test‘, // 后台请求路径 //请求参数 data:{ username:request.term//请求参数.换成$("#username").val()一样 }, //data为返回数据(json) success: function( data ) {//回调函数 var d = JSON.parse(data);//将 JSON 字符串转换为对象 response(d);//响应 } }); } }); }); </script> </head> <body> 用户名:<input type="text" name="username" id="username" /> </body> </html>
2、json的必须包,jquery-ui-1.10.4.custom.css,jquery-ui-1.10.4.custom.js
3、Test.java
package com.xtkj.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; public class Test extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String username = new String(request.getParameter("username").getBytes("iso8859-1"),"utf-8"); response.setContentType("text/html;charset=utf-8"); //看成数据库的数据 List list = new ArrayList(); list.add("jack"); list.add("tom"); list.add("toy"); list.add("json"); list.add("lily"); list.add("lucy"); //看成模糊匹配数据库返回的集合 List li = new ArrayList(); for(int i=0;i<list.size();i++){ if(list.get(i).toString().indexOf(username)!=-1){ li.add(list.get(i)); } } //将list转json JSONArray json = JSONArray.fromObject(li); PrintWriter out = response.getWriter(); out.print(json); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
标签:rac test $.ajax nal servlet net cti erp ram
原文地址:http://www.cnblogs.com/Vito-Yan/p/7534156.html