囍相逢²LIQP 2013-04-06 22:53
浏览 280
已采纳

html文件利用ajax方法 通过 servlet 获取数据库信息 显示乱码,求解?

html文件利用ajax方法 通过 servlet 获取数据库信息 显示乱码,求解?

suggest.html:



    <style type="text/css" media="screen">
        body {
            font: 11px arial;
        }
        .suggest_link {
            background-color: #FFFFFF;
            padding: 2px 6px 2px 6px;
            cursor:hand;
        }
        .suggest_link_over {
            background-color: #E8F2FE;
            padding: 2px 6px 2px 6px;
        }
        #search_suggest {
            position:relative;
            background-color: #FFFFFF;
            text-align: left;
            border: 1px solid #000000;
            left: -12px;
            top: 1px;
            height: 74px;
            width: 170px;
            display:none;
        }       
    </style>
</head>
<body background="bg.gif">
<center>
    <h3>实现搜索提示</h3>
    <div style="width: 500px;">
            <input type="text" id="txtSearch" name="txtSearch" onKeyUp="searchSuggest();" autocomplete="off" />
            <input type="submit" id="cmdSearch" name="cmdSearch" value="搜索"/><br />
            <div id="search_suggest"></div>
    </div>
    </center>
</body>

ajax_search.js:
var searchReq = createAjaxObj();
function createAjaxObj()
{
var httprequest=false;
if (window.XMLHttpRequest) //为非IE浏览器生成XmlHttpRequest对象
{
httprequest=new XMLHttpRequest()
if (httprequest.overrideMimeType) httprequest.overrideMimeType('text/xml')
}
else if (window.ActiveXObject) //为IE浏览器生成XmlHttpRequest对象
{
try
{
httprequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httprequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return httprequest
}
function searchSuggest()
{
if (searchReq.readyState == 4 || searchReq.readyState == 0)
{
var str = document.getElementById('txtSearch').value;
[b]searchReq.open("GET", 'search?search=' + str, true);//向服务器端发送请求[/b] searchReq.onreadystatechange = handleSearchSuggest; //设置回调函数
searchReq.send(null);
}

}
function handleSearchSuggest()
{ //这是回调函数,处理从服务器端返回的信息
if (searchReq.readyState == 4)
{
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for(i=0; i < str.length - 1; i++)
{
var suggest = '

suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '
';
ss.innerHTML += suggest;
ss.style.display="block";
}
}
}
function suggestOver(div_value)
{
div_value.className = 'suggest_link_over';
}
function suggestOut(div_value)
{
div_value.className = 'suggest_link';
}
function setSearch(value)
{
document.getElementById('txtSearch').value = value;
document.getElementById('search_suggest').innerHTML = '';
document.getElementById('search_suggest').style.display="none";
}

Servlet文件SearchSuggest.java:
package com;

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 javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SearchSuggest extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException
{
String search = request.getParameter("search"); //接受参数值

    String sql = "select GoodsName from Goods where GoodsName like '"+search+"%' order by GoodsName";//设置查询语句
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    ArrayList vData = new ArrayList();
    java.io.PrintWriter out = response.getWriter();
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //注册数据库连接驱动

        String MdbPath = "F:/shop.mdb"; 
        String url= "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + MdbPath ; 
        conn = DriverManager.getConnection(url);    

        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql); //执行查询
        while (rs.next())
        {
            vData.add(rs.getString("GoodsName"));
        }
        StringBuilder buf = new StringBuilder();
        for (int i=0;i<vData.size();i++)
        {
            String keyword = (String)vData.get(i);
            buf.append(keyword+"\n");
        }
        out.print(buf.toString());//向客户端输出信息
    } catch (Exception e) {
            e.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        } catch (SQLException sqle) {
        }
    }
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException 
{
    doPost(request, response);
}

}

效果图:

[img]http://dl.iteye.com/upload/attachment/0082/7129/bd3b22cd-f7f5-3ec1-8a06-3daca35838e1.png[/img]

  • 写回答

2条回答 默认 最新

  • Dead_Knight 2013-04-07 10:33
    关注

    String search = request.getParameter("search"); //接受参数值
    这句代码上面加上一句:
    response.setCharacterEncoding("UTF-8");
    意思就是响应结果为utf-8编码。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vue使用gojs,需求在link中的虚线上添加方向箭头
  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红