2013-08-27 26 views
0

我在Java中使用JSP + JavaScript + Servlet進行項目,並在JavaScript中使用函數來查找數據庫中的某條記錄。當找到這條記錄時,我的函數會返回一些值,如果沒有,我的函數會返回一條消息。現在我需要另一個函數來從我的數據庫中返回幾個字段,我不知道是誰。我對JavaScript和JSP不是很熟悉。
編輯:我做了一些變化具有多值的函數JavaScript + JSP + Servlet

這是從我的JSP代碼的一部分:

<% 
    HashMap row = new HashMap(); 
%> 
<tr> 
    <td> 
    <input type='text' id="noeco" name="noeco" size=5 maxlength=5 onkeyup="find_noeco_s(noeco,row);"> 
    <span name="exists" id="exists" readonly="readonly" style="width: 200px" value='{row.get("exists")}'></span></input>        
    </td> 
</tr> 
<tr> 
    <td> 
    <input type='text' id="matric" name="matric" readonly="readonly" value="{row.get('matri')}"></input> 
    </td> 
</tr> 
<tr> 
    <td> 
    <input type='text' id="marca" name="marca" readonly="readonly" value="{row.get('marca')}"></input> 
    </td> 
</tr> 

這是我的JavaScript函數 「find_noeco_s」:

function find_noeco_s(noeco,row){ 
    objsal = row; 
    if(window.XMLHttpRequest) 
     ajax = new XMLHttpRequest(); 
    else 
     ajax = new ActiveXObject("Microsoft.XMLHTTP"); 
    ajax.onreadystatechange = funcionCallback; 

    ajax.open("GET", "/processEco.jsp?noeco="+noeco.value, true); 
    ajax.send(""); 

}

而且這是我的JSP過程生態環境:

String noeco = request.getParameter("noeco"); 
String exists=""; 
String matri= ""; 
HashMap row = new HashMap(); 
try{ 
    PreparedStatement ps = PV.prepareStatement("select * from vehicles where econom=?"); 
    ps.setString(1, noeco); 
    ResultSet rs = ps.executeQuery(); 
    if(rs.next()){ 
     exists= rs.getString("dstipveh"); 
     matri = rs.getString("matr"); 
     marca= rs.getString("marca"); 
     row.put("exists", exists); 
     row.put("matr", matr); 
     row.put("marca", marca); 
    }else{ 
     exists= "DOES NOT EXISTS"; 
     row.put("exists", exists); 
    } 
%> 
<%=row%> 
<% 
}finally{}  
%> 

但我只得到一個值(存在)。就像我說的,我對JavaScript和JSP不是很熟悉。那麼,如何返回多個值並在JSP中顯示這些值,就像我僅使用一個值一樣?

回答

0

根據您的問題要求,將所有字段放到一個對象中,並從您的方法調用中返回該對象。

e.g:

Class MyReturnTypeData { 
    private String exists; 
    private String matr; 
    private String marca; 
    .... 

    } 
0

一種方法是使用HashMap。

HashMap row = new HashMap(); 
if(rs.next()){ 
exists= rs.getString("dstipveh"); 
matri = rs.getString("matr"); 
marca= rs.getString("marca"); 
row.put("exists", exists); 
row.put("matr", matr); 
row.put("marca", marca); 
} 
else 
{ 
exists= "DOES NOT EXISTS"; 
row.put("exists", exists); 
} 
return row; 

然後檢索值

<% 
if (row.get("exists").equals("DOES NOT EXISTS")) 
{ 
out.println(row.get("exists")); 
} 
else 
{ 
out.println(row.get("exists")); 
out.println(row.get("matr")); 
out.println(row.get("marca")); 
} 
%> 
+0

謝謝。我做了一些像你一樣的改變,但「行」總是空的,我無法在JSP中顯示值。就像我說的,我對JSP和JS不是很熟悉。我錯過了什麼? – user1600801

+0

是數據庫查詢發生在你試圖顯示值的地方的獨立方法中,還是它們發生在同一個方法中? – chiliNUT

+0

用另一種方法......我的第一個代碼是我的JSP,它顯示值(表單JSP)。我的第二個代碼是mi JS(其中find_noeco_s函數是),在我的JSP中調用,第三個代碼是從我的JS(processEco.jsp)調用的另一個JSP, – user1600801