English 中文(简体)
从由 Javascript 和 Java 返回的数组中弹出一个从 rara 降下来的投影
原标题:Populating a DropDown from an Array returned by Javascript and Java

在 HTML 中我得到了一个下调, 需要动态地从数据库中输入用户标识列表。 因此, 我需要执行 JavaScript 函数在 HTML 页面加载之前调用 Java 函数以查询 DB 。 由于我需要在加载页面之前执行 JS 函数, 我将头部分的 Javascript (用户. js) 导入头部分, 并调用我的 JS 函数 ( findedAgentications request (找到 Agencyorganications) on the HTML 体标记中 atload () 方法 。

<!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=ISO-8859-1">
    <title>Sample User Registration</title>     
    <script language="javascript" src="js/Users.js"> </script>
</head>

<body atload="findActiveUsersRequest(findActiveUsers)">
    <H2>User Registration</H2>                        
    <div id="userAccessForm" >
 <form name="userAccessForm" id="userAccessForm">
<div id="userAccessResults" style=" width : 364px; float:left;"></div><br>      <table width="100%" border="1px">
<tr><td>    <p>Organisation *<br>
    <select name="UserID" id="UserID">                  <option value="Choose your Organisation" selected>Choose Username</option>
    <option value="1">Dynamically populate User1</option>                   <option value="2">Dynamically populate User2</option>                   <option value="3">Dynamically populate user3</option>                   </select>   </p><td>
<input name="submit" type="submit" id="submit" value="Submit">              <input name="reset" type="reset" id="cancel" value="Cancel">
</td></tr>
<tr><td>
<div id="UserResults" style=" width:353px; float:left;"></div></td></tr>
</table>
</form></body>

function findActiveUsersRequest(findActiveUsers){
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
    var returnText = xmlhttp.responseText;
    document.getElementById("UserResults").innerHTML=returnText;
};

var loadingHtml = "<img border="0" src="images/busy.gif" width="50" /> Active Users Details...";
document.getElementById("UserResults").innerHTML=loadingHtml;
xmlhttp.open("GET","mets?action=users&userAction="+findActiveUsers);    
xmlhttp.send(); 
}

显而易见,上述联署材料职能的最后两行发送了HTTP请求,被服务器抓住,然后:

  1. 检查 HTTP 请求中的参数,

  2. 从数据库获取结果

  3. 创建 < code> StringBuffer 阵列, 以“ UserID - UserID - UserName” 的格式回应。 但我不确定这是否是这样做的最佳方式。 任何帮助/ 建议都将非常感激!

  4. 发送回复如下: sendResponse (回复.getWriter (), 字符串Buffer)

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

public class RequestActionFactory {
@SuppressWarnings("unchecked")
public static Action getAction(HttpServletRequest request) {
    // Retrieve action parameters
    String action = request.getParameter("action");
    String userAction = request.getParameter("UserAction");


              // Validate
    if (action != null) {
        // Event request
        if (action.equals("users")) {
            List<UserIdDTO> userDTOList = getActiveUsers(); //Gets the UserIds from the DB
            StringBuffer[] stringBuffer = new StringBuffer[userDTOList.size()];                         
            for (UserIdDTO userDTO : userDTOList) {
                for(int i=0; i<userDTOList.size(); i++) {
                    stringBuffer[i] = new StringBuffer();
                    stringBuffer[i].append(responseValue(userDTO));
                }
            }           
            sendResponse(response.getWriter(), stringBuffer); 
        } 
    }       
    return null;        
}

private StringBuffer responseValue(UserIdDTO userDTO){
    StringBuffer strBuffer = new StringBuffer();
    strBuffer.append(userDTO.getId());
    strBuffer.append(" - ");
    strBuffer.append(userDTO.getuserName());        
    return strBuffer;
}   

public static void sendResponse(PrintWriter writer, StringBuffer[] stringBuffer) {
    if (stringBuffer != null) {         
            for(int i=0; i<stringBuffer.length; i++) {                  
                if(null!=stringBuffer[i]) {
                    writer.write(stringBuffer[i].toString());
            }   
        } 
    } else {
        // TODO write to log            
    }       
}   
}

Java Serverlet公司一旦回信答复,就会陷入上述联署材料职能,即:

xmlhttp.onreadystatechange = function() {
    var returnText = xmlhttp.responseText;
    document.getElementById("UserResults").innerHTML=returnText;
};

因此,我成功地将阵列显示在我的窗体上的用户Results DIV 标记中,显示为:

- 1个约翰·史密斯

- 亚当·史密斯

彼得·史密斯 3 - 彼得·史密斯

但我怎么用这个阵列 来填充我的表情呢?

任何帮助都会感激不尽!

问题回答

要称呼您 js 函数使用 jQuery :

jQuery(document).ready( function() {
    // You init code here
});

Use json to serialize your collection from java and deserialize it on javascript side. On java side to serialize to json:

Collection<YourType> myCollection = ... ;
Gson gson = new Gson();
String json = gson.toJson(myCollection);

// Write json to response

js 侧面 :

var myCollection = JSON.parse(responseText);
for(i = 0l i < myCollection.length; i++) {
    var element = myCollection[i];
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签