Ajax-ajax執行個體1-動態載入的 FAQ

來源:互聯網
上載者:User

標籤:運行   ams   jdbc   get   highlight   string   調用   jdb   als   

動態載入 FAQ 的過程主要是利用 XMLHttpRequest(以下簡稱 XHR)對象與服務端通訊,根據用戶單擊的感興趣問題動態將內容載入到頁面中。在具體實現時,有兩點要注意的內容。

1 .對每個問題進行唯一標識
FAQ 主要包含問題與解答兩個部分,使用者單擊一個問題時,伺服器必須知道請求的是哪個問題的
解答,所以必須對每個問題進行唯一標識。標識的方法很多,在本例中簡單使用數字進行標識。每個
問題在頁面上表現為超連結,單擊連結將觸發 onclick 事件,調用 loadFAQ 函數,傳入問題標識,擷取
對應的解答。
單擊後並不是要真正連結到一個新的頁面,所以在<a>標籤的 onclick 事件中 return false 取消原有
連結的功能。每個答案分配一個 div 用於顯示,每個 div 的 id 屬性命名規則為,在對應的問題數字標
識前統一增加“faqDetail”。
2 .對已載入的解答不重複向伺服器發出請求
問題的解答載入後,將顯示在對應問題下方的 div 中。當使用者再次單擊問題時該 div 將隱藏起來。
如果使用者第三次單擊相同的問題,由於解答已載入到頁面,所以不需要再次向伺服器發送請求,只需
將隱藏的 div 顯示出來即可。
隱藏和顯示主要通過設定 div 樣式中的 display 屬性來完成,當 display 屬性設定為“none”時隱藏,
設定為“block”時顯示。判斷是否需要發出請求,可以檢查 div 的 innerHTML 是否包含內容。

項目結構:

 

項目運行:

 

AjaxRequest.js:Ajax封裝類: http://www.cnblogs.com/hfultrastrong/p/7267171.html

 

showfaq.jsp:用於顯示faq問題:

<%@page import="java.sql.ResultSet"%><%@page import="java.sql.PreparedStatement"%><%@page import="java.sql.Connection"%><%@page import="com.gordon.util.DBUtil"%><%@ 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><body><%Connection conn = DBUtil.getConnection();String sql = "SELECT * FROM faqdetail;";PreparedStatement pst = conn.prepareStatement(sql);ResultSet rs = pst.executeQuery(sql);while (rs.next()) {%><a href="javascript:;" onclick="getFaqDetail(<%=rs.getString("id")%>);return false;"><%=rs.getString("answer")%></a><br><div id="faqdetail<%=rs.getString("id")%>" style="display: none;"></div><br /><hr /><%}rs.close();pst.close();conn.close();%></body><script type="text/javascript" src="js/AjaxRequest.js"></script><script type="text/javascript">// 建立XMLHttpRequest隨想var xhr = Ajax();// 根據問題id擷取詳細內容function getFaqDetail(answerid) {var shownode = document.getElementById("faqdetail" + answerid);if(shownode.style.display == "none") {shownode.style.display = "block";if(shownode.innerHTML == "") {var url = "GetFaqDetailServlet";var params = "answerid=" + answerid;var des_url = url + "?nocache=" + new Date().getTime() + "&" + params;xhr.get(des_url, function(data){handleResult(data, shownode);});}} else {shownode.style.display = "none";}}// 處理返回結果function handleResult(data, shownode) {shownode.innerHTML = data;}</script></html>

 

GetFaqDetailServlet.java:用於邏輯處理:

package com.gordon.servlet;import java.io.IOException;import javax.servlet.Servlet;import javax.servlet.ServletConfig;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.gordon.service.GetAnswerDetailService;/** * 擷取FAQ問題詳情 */@WebServlet(urlPatterns = { "/GetFaqDetailServlet" })public class GetFaqDetailServlet extends HttpServlet {private static final long serialVersionUID = 1L;/** * @see HttpServlet#HttpServlet() */public GetFaqDetailServlet() {super();// TODO Auto-generated constructor stub}/** * @see Servlet#init(ServletConfig) */public void init(ServletConfig config) throws ServletException {// TODO Auto-generated method stub}/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse *      response) */protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String question = ""; request.setCharacterEncoding("UTF-8");response.setContentType("text/text;charset=utf-8;");String answerid = request.getParameter("answerid");try {question = GetAnswerDetailService.getAnswerDetailById(answerid);} catch (Exception e) {System.out.println(e.getMessage());}response.getWriter().print(question);}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse *      response) */protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

 

GetAnswerDetailService.java:用於根據id擷取答案的詳細代碼結構:

package com.gordon.service;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import com.gordon.util.DBUtil;public class GetAnswerDetailService {/** * 根據問題id擷取解答資訊 * @param answerid * @return * @throws ClassNotFoundException * @throws SQLException */public static String getAnswerDetailById(String answerid) throws ClassNotFoundException, SQLException {String result = "";Connection conn = DBUtil.getConnection();String sql = "SELECT question FROM faqdetail WHERE id = ?";PreparedStatement pst = conn.prepareStatement(sql);pst.setInt(1, Integer.valueOf(answerid));ResultSet rs = pst.executeQuery();while (rs.next()) {result = rs.getString("question");}rs.close();pst.close();conn.close();return result;}}

 

DBUtil.java用於擷取資料庫連接:

package com.gordon.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class DBUtil {private static final String URL = "jdbc:mysql://localhost:3306/ajaxexample_1";private static final String DRIVER = "com.mysql.jdbc.Driver";private static final String USERNAME = "root";private static final String PASSWORD = "root";public static Connection getConnection() throws ClassNotFoundException, SQLException {Class.forName(DRIVER);return DriverManager.getConnection(URL, USERNAME, PASSWORD);}}

 

+++++++++++++++++++++++++++

 

參考:ajax實用案例大全-1動態載入資料  https://wenku.baidu.com/view/c7897bf4700abb68a982fb91.html

 

Ajax-ajax執行個體1-動態載入的 FAQ

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.