Ajax和Json實現自動補全
阿新 • • 發佈:2017-09-17
scrip serve rds data character style pragma get writer
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); } }
Ajax和Json實現自動補全