1. 程式人生 > >ajax 動態獲取數據庫中的值

ajax 動態獲取數據庫中的值

on() click black .get solver 關閉連接 SQ system ppi

功能簡介: 在一個輸入框中輸入內容 ,當內容長度>1時向後發送ajax 從數據庫中獲取有關文本框中的內容在前臺顯示, 前臺設計一些點擊事件,以及jquery的應用

1 使用了springmvc 中的requestmapping註解 故 先附上 配置文件

web.xml配置:

<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

 

springmvc.xml配置如下:
<!-- 配置自定掃描的包 -->
	<context:component-scan base-package="com.rl.util"></context:component-scan>

	<!-- 配置視圖解析器: 如何把 handler 方法返回值解析為實際的物理視圖 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

  

前臺頁面如下:

<%@ 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>
<style>
			input[name]{
				width:500px;
				height: 20px;
				align-self: center;
				vertical-align:middel;
				margin-left:300px;
			}
			
			#div1{
				width: 500px;
				height: 230px;
				border: 1px solid black;
				list-style:none;
				margin-left:300px;
				display: none;
				
			}
			.mouseOver{
				background-color: red;
			}
		</style>
		<script type="text/javascript" src="static/bootstrap/js/jquery.min.js" ></script>
</head>
<body>
	<input id="sousuo" type="text" name="inputText" placeholder="請輸入" />
		<input type="button" value="搜索" />
		<br>
	<div id="div1">
			<li>北京</li>
			<li>天?</li>
			<li>上?</li>
			
	</div>
	
	 <a href="ad">dasf</a>
</body>
<script>
		$("#sousuo").focus();
			$("#sousuo").blur(function(){
					$("#div1").hide(1000);
			})
		$(document).ready(function(){
			$("#sousuo").bind("keyup",function(){
			var $inpu=$("#sousuo").val();
						
				if($inpu.length>1){
					//alert($inpu);

					$.ajax({
			            async : false,
			            cache : false,
			            type : ‘POST‘,
			            url : ‘/ajax_jso/ad‘,
			            dataType : "json",
			          	data : {"postData":$inpu},            
			            error : function() {
			                alert(‘請求失敗 ‘);
			            },
			            success : function(data) {
			              /*  */
			               $("li").text("");
			               for(var i=0;i<data.length;i++){
			            	  /*  . */
				               var $li = $("<li></li>");
				               $li.text(data[i]);
				               $("#div1").append($li);
			               }
			               
			            }

			        });
					
					$("#div1").show(1000)
					//setTimeout(,5000)
					
				}
				
				$("li").mouseover(function(){
					$("li").removeClass();		
					$(this).addClass("mouseOver");
					
				});
				$("li").click(function(){
					$("#sousuo").val($(this).text());
				})
			});
			
			
		});
			
			
			
	</script>
</html>

  後臺接受請求的代碼如下:

package com.rl.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import net.sf.json.JSONArray;

@Controller
public class Control {
	@RequestMapping("/ad")
	@ResponseBody
	public 	String  getList(HttpServletRequest request) {
		//HttpServletRequest request=  ServletActionContext.getRequest();  
		List<String> list=new ArrayList<>();
		Gson gson2 = new GsonBuilder().enableComplexMapKeySerialization().create(); 
		try {
			
			Class.forName("com.mysql.jdbc.Driver");// 導入驅動(jar包)
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		String name = "";
		Connection conn = null;
		try {
			conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/xxff", "root", "123456");// 建立連接
		} catch (SQLException e) {
			e.printStackTrace();
		}

		// String sql = "select name,email,dob from student";//建立SQL語句
		System.out.println( request.getParameter("postData"));
		  String postData =  request.getParameter("postData");  
		  if(postData==null){
			  System.out.println("null    "+"postData");
		  }
		  
		  else{
			  postData = postData.trim();
			  System.out.println("TrubleShooting.java  timestap = "+postData);
				String sql = "SELECT  login_name FROM tab_account WHERE login_name LIKE ‘%"
						+ ""
						+postData+ "%‘";//where login_name like ‘%postData%‘
				/*List<Map<String, String>> list = new ArrayList<>();
				Map<String, String> map = new HashMap<>();
				*/
				
				try {
					Statement stmt = (Statement) conn.createStatement();
					ResultSet rs = stmt.executeQuery(sql);
					// cursor
					while (rs.next()) {
						name = rs.getString(1);
						//list.add(name);
						/*
						 * String email = rs.getString(2); String dob = rs.getString(3);
						 */
						//System.out.println(name/* +" , "+email+" , "+dob */);
						System.out.println(name);
						//map.put("name", name);
						list.add(name);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					if (conn != null)
						try {
							conn.close();// 關閉連接
						} catch (SQLException e) {
							e.printStackTrace();
						}
				}
		  }
		 
		String json=JSONArray.fromObject(list).toString();
		JSONArray jsonArray = JSONArray.fromObject(json);
		 //List<String> list2 = (List) JSONArray.toCollection(jsonArray);
		return json;
	}
}

  

ajax 動態獲取數據庫中的值