1. 程式人生 > >利用JQuery傳送ajax請求進行站內搜尋

利用JQuery傳送ajax請求進行站內搜尋

前臺程式碼:(注意要匯入JQuery包,在lib中也要匯入gson-x.x.x.jar包

<%@ 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>
</head>
<script type="text/javascript" src="JS/jquery-1.11.0.js"></script>
<script type="text/javascript"> //為搜尋繫結聚焦事件 $(function(){ $("#search").keyup(function(){ var content = $(this).val(); var returnStr = ""; $.post( "/ajax_backstage1/ajaxServlet", {"content":content}, function(data){ if(data.length>0){ for(var i=0;i<data.length;i++){ returnStr += "<div id='div' style='padding:5px;cursor:pointer' onmouseover='overFn(this)' onmouseout='outFn(this)' onclick='clickFn(this)'>"+data[i]+"</div>";// } $("#div").html(returnStr); $("#div").css("display","block"); }else{ $("#div").css("display","none"); } }, "json" ); }); $("#search").blur(function(){ $("#div").css("display","none"); }); }) //繫結按鈕事件 $(function(){ $("#button").click(function(){ var sub = $("#search").val(); $.ajax({ type:"POST", url:"{pageContext.request.contextPath}/ajaxServlet", contentType:"application/json", data:JSON.stringify({"sub":sub}), dataType:"json", success:function(result){ //請求正確後的操作 }, error:function(result){ //請求失敗後的操作 } }); }); }) //對div新增滑鼠移入效果 function overFn(obj){ $(obj).css("background-color","yellow"); } //對div新增滑鼠移出效果 function outFn(obj){ $(obj).css("background-color","#F0F8FF"); } //對div內容新增點選效果 function clickFn(obj){ $("#search").val($(obj).html()); $("#div").css("display","none"); } </script> <body> <input type="text" id="search" /><input type="button" id="button" value="按鈕"> <div id="div" style="width:150px;display:none;background-color: #F0F8FF"></div> </body> </html>


這裡因為後臺是為了測試前臺ajax提交是否成功,這裡為了方便,避免不必要的導包操作,用之前寫過的最原始的方法測試,
下面是後臺MVC分層思想的Servlet+JDBC程式碼

servlet層:

package action;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import service.SearchService;

/**
 * Servlet implementation class ajaxServlet
 */
public class ajaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @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 {
		//從前臺獲取json格式資料
		request.setCharacterEncoding("UTF-8");
		String content = (String) request.getParameter("content");
		//建立一個service類,並呼叫其查詢方法
		SearchService ss = new SearchService();
		List<String> list = null;
		try {
			list = ss.search(content);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(list);
		//將service返回的資料進行格式轉換變成json
		//先建立一個Gson
		Gson gson = new Gson();//這裡沒有gson導包操作會報錯
//然後解析獲得的list,把json轉換成string String str = gson.toJson(list); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(str); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }


service層:

package service;

import java.sql.SQLException;
import java.util.List;
import dao.SearchDao;

public class SearchService {

	public List<String> search(String content) throws SQLException {
		// TODO Auto-generated method stub
		SearchDao sd = new SearchDao();
		List<String> list = sd.search(content);
		return list;
	}
	
}

dao層:

package dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import utils.DataBaseUtil;

public class SearchDao extends DataBaseUtil {

	public List<String> search(String content) throws SQLException {
		// TODO Auto-generated method stub
		List<String> list = new ArrayList<String>();
		String sql = "select * from cst_linkman where lkm_name like '%"+content+"%'" ;
		rs = commonQuery(sql);
		while(rs.next()){
			list.add(rs.getString("lkm_name"));
		}
		return list;
	}

}


Utils:

package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DataBaseUtil {
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String DRIVER_URL = "jdbc:mysql://127.0.0.1:3306/test";
	private static final String DRIVER_USER = "root";
	private static final String DRIVER_PWD = "123";
	protected Connection conn=null;
	protected PreparedStatement pst=null;
	protected ResultSet rs=null;
	
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//連結資料庫
	public static Connection getConnection(){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(DRIVER_URL,DRIVER_USER,DRIVER_PWD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	//查詢
	public ResultSet commonQuery(String sql,Object...params) throws SQLException{
		conn = getConnection();
		pst=conn.prepareStatement(sql);
		if(params !=null && params.length>0){
			setValue(pst,params);
		}
		rs=pst.executeQuery();
		return rs;
	}
	
	//增刪改
	public int commonUpdate(String sql,Object...params) throws SQLException{
		int result =0;
		conn=getConnection();
		try {
			pst=conn.prepareStatement(sql);
			if(params !=null && params.length>0){
				setValue(pst,params);
			}
			result=pst.executeUpdate();
		}finally{
			closeAll(conn, pst, rs);
		}
		return result;
	}
		
	private void setValue(PreparedStatement pst2, Object[] params) throws SQLException {
		for(int i=0;i<params.length;i++){
			pst2.setObject(i+1, params[i]);
		}
	}

	//關閉資料庫
	public void closeAll(Connection conn,PreparedStatement pst,ResultSet rs){
		try {
			if(rs !=null){
				rs.close();
			}
			if(pst !=null){
				pst.close();
			}
			if(conn !=null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}

另外,這裡用的是2.5版本的web專案,程式碼沒有添加註解,對映servlet的web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ajax_backstage1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ajaxServlet</display-name>
    <servlet-name>ajaxServlet</servlet-name>
    <servlet-class>action.ajaxServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ajaxServlet</servlet-name>
    <url-pattern>/ajaxServlet</url-pattern>
  </servlet-mapping>
</web-app>