Javascript 单击复选框后向服务器发送命令

Javascript 单击复选框后向服务器发送命令,javascript,html,jsp,checkbox,jstl,Javascript,Html,Jsp,Checkbox,Jstl,我正在开发一个应用程序,其中我有一个带有动态生成表(使用jstl生成)的jsp页面,其中每个单元格都有一个复选框。当我标记此复选框时,我需要向数据库触发一个事件以在表中插入一行。如果取消标记该复选框,则应删除此行。有人知道怎么做吗?我的想法是,我应该使用一些ajax代码来实现这一点,但我不知道从哪里开始。有人可以给我一些想法(甚至不需要代码,我想一种算法就足够了) 我遵循Matej Chrenko先生的建议,编写以下代码: <%@ page language="java" content

我正在开发一个应用程序,其中我有一个带有动态生成表(使用jstl生成)的jsp页面,其中每个单元格都有一个复选框。当我标记此复选框时,我需要向数据库触发一个事件以在表中插入一行。如果取消标记该复选框,则应删除此行。有人知道怎么做吗?我的想法是,我应该使用一些ajax代码来实现这一点,但我不知道从哪里开始。有人可以给我一些想法(甚至不需要代码,我想一种算法就足够了)


我遵循Matej Chrenko先生的建议,编写以下代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="jquery-1.11.0.min.js"> </script>
<script>
$(".checkbox").change(function() {
    if(this.checked) {
        window.alert("unmarked");
    } else{
        window.alert("marked");
    }
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cadastra Horario Livre</title>
</head>
<body>

<p align="center">
<span class="usuario">${nome}</span> | <strong> Hora Livre</strong> | <a href="/hora_livre/ProcessaSaida"> Sair</a>
</p>

<p align="center">

<form method="post" action="">
<table border = 2>

<tr>
    <th>  </th>
    <c:forEach var="item" items="${list2}">
        <th> <c:out value="${item}"/> </th>
    </c:forEach>
</tr>

<c:forEach var="item2" items="${list}">
<tr>
    <td> <c:out value="${item2}"/> </td>
    <c:forEach var="item" items="${list2}">
        <td> <input type="checkbox"> </td>
    </c:forEach>
</tr>
</c:forEach>

</table>
</form>

</p>

</body>
</html>

$(“.checkbox”).change(函数(){
如果(选中此项){
窗口警报(“未标记”);
}否则{
窗口。警报(“标记”);
}
});
霍拉里奥·利弗尔地籍

${nome}Hora Livre

但是,当我单击复选框时,什么也没有发生。我做错了什么?(我将jquery文件添加到我的项目的WEB-INF文件夹中-此jsp位于同一位置)。

此:

 $(".checkbox").change(function() {
        if(this.checked) {
            //Do stuff
        } else{
            //unchecked
        }
    });
这是:


会帮助您的。

我认为Ajax是可能的解决方案。您可以使用jQuery来简化这一过程


您可以参考

好的,我通过更改用于将请求发送到服务器的javascript代码来解决问题。我按照你的指示去做

JSP页面的代码以如下方式结束:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script type="text/javascript" src="<c:url value='/js/ajax.js'/>"></script>
<script>
function handleClick(cb, idevento, data, hora) {
    if(cb.checked) {
        alert("marked "+data+" "+hora+" for "+idevento);
        sendAjaxRequest("/hora_livre/CadastraHoraLivre?target=cadastra&data="+data+"&hora="+hora+"&evento="+idevento, "showdetails");
    } else{
        alert("unmarked "+data+" "+hora+" for "+idevento);
        sendAjaxRequest("/hora_livre/CadastraHoraLivre?target=remove&data="+data+"&hora="+hora+"&evento="+idevento, "showdetails");
    }
}
</script>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cadastra Horario Livre</title>
</head>
<body>

<p align="center">
<span class="usuario">${nome}</span> | <strong> Hora Livre</strong> | <a href="/hora_livre/ProcessaSaida"> Sair</a>
</p>

<p align="center">

<table border = 2>

<tr>
    <th>  </th>
    <c:forEach var="item" items="${list2}">
        <th> <c:out value="${item}"/> </th>
    </c:forEach>
</tr>

<c:forEach var="item2" items="${list}">
<tr>
    <td> <c:out value="${item2}"/> </td>
    <c:forEach var="item" items="${list2}">
        <td> <input type="checkbox" id="checkbox" onclick="handleClick(this, '${id}', '${item2}', '${item}')"> </td>
    </c:forEach>
</tr>
</c:forEach>

</table>

<div id="showdetails"> </div>

</p>

</body>
</html>

函数handleClick(cb、idevento、data、hora){
如果(cb.选中){
警报(“标记为“+data+”+hora+”表示“+idevento”);
sendAjaxRequest(“/hora_livre/CadastraHoraLivre?target=cadastra&data=“+data+”&hora=“+hora+”&evento=“+idevento,”showdetails”);
}否则{
警报(“未标记的”+数据+“”+hora+”表示“+idevento”);
sendAjaxRequest(“/hora_livre/CadastraHoraLivre?target=remove&data=“+data+”&hora=“+hora+”&evento=“+idevento,”showdetails”);
}
}
霍拉里奥·利弗尔地籍

${nome}Hora Livre

页面中包含的文件ajax.js是:

/* common method to get XMLHttp request object */

function getXMLHttpRequest() {
    var req;
    if (window.XMLHttpRequest) { // For Firefox, Mozilla, Safari, …
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) { // For IE
        try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                //
            }
        }
    }
    return req;
}

/* method for dynamically getting current time in milliseconds and append that value to no-cache parameter
* IE browser does not send ajax request if the url is same, simply get result from cache
* to avoid this and make a new request, we append no-cache param to each ajax request.
*/

function getNoCacheValue(url)
{
    var d = new Date();
    var appendstring = (url.indexOf("?") != -1) ? "&" : "?";
    var nocachevalue = appendstring + "no-cache=" + d.getTime();
    return nocachevalue
}

/* method to send a ajax request, and write the response text to given divid. */

function sendAjaxRequest(url, divid) {
    url = url + getNoCacheValue(url);
    var req = getXMLHttpRequest();
    req.onreadystatechange = function() {
        processResponse(req, divid)
    };
    req.open('GET', url, true);
    req.send(null);
}

function processResponse(req, divid) {
    if (req.readyState == 4) {
        if (req.status == 200) {
            document.getElementById(divid).innerHTML=req.responseText;
            invokeScript(document.getElementById(divid));
        }
    }
}

/* method for executing script separately.
* (scenario :  send a Ajax request, response is HTML with some scripts – scripts in response HTML should not load )
* to overcome this issue, we used this method to load the scripts separately.
*/

function invokeScript(divid) {
    var scriptObj = divid.getElementsByTagName("SCRIPT");
    var len = scriptObj.length;
    for(var i=0; i<len; i++) {
        var scriptText = scriptObj[i].text;
        var scriptFile = scriptObj[i].src
        var scriptTag = document.createElement("SCRIPT");
        if ((scriptFile != null) && (scriptFile != "")) {
            scriptTag.src = scriptFile;
        }
        scriptTag.text = scriptText;
        if (!document.getElementsByTagName("HEAD")[0]) {
            document.createElement("HEAD").appendChild(scriptTag)
        }
        else {
            document.getElementsByTagName("HEAD")[0].appendChild(scriptTag);
        }
    }
}
/*获取XMLHttp请求对象的常用方法*/
函数getXMLHttpRequest(){
var-req;
如果(window.XMLHttpRequest){//对于Firefox、Mozilla、Safari…
req=新的XMLHttpRequest();
}
else if(window.ActiveXObject){//For IE
试一试{
req=新的ActiveXObject(“Msxml2.XMLHTTP”);
}
捕获(e){
试一试{
req=新的ActiveXObject(“Microsoft.XMLHTTP”);
}
捕获(e){
//
}
}
}
返回请求;
}
/*方法动态获取以毫秒为单位的当前时间,并将该值附加到no cache参数
*如果url相同,IE浏览器不会发送ajax请求,只需从缓存中获取结果即可
*为了避免这种情况并发出新请求,我们不对每个ajax请求附加任何缓存参数。
*/
函数getNoCacheValue(url)
{
var d=新日期();
var appendstring=(url.indexOf(“?”)=-1?“&”:“;
var nocachevalue=appendstring+“no cache=“+d.getTime();
返回nocachevalue
}
/*方法发送ajax请求,并将响应文本写入给定的divid*/
函数sendAjaxRequest(url,divid){
url=url+getNoCacheValue(url);
var req=getXMLHttpRequest();
req.onreadystatechange=函数(){
processResponse(请求,divid)
};
请求打开('GET',url,true);
请求发送(空);
}
函数processResponse(req,divid){
如果(req.readyState==4){
如果(请求状态==200){
document.getElementById(divid).innerHTML=req.responseText;
invokeScript(document.getElementById(divid));
}
}
}
/*方法分别执行脚本。
*(场景:发送Ajax请求,响应是带有一些脚本的HTML–响应HTML中的脚本不应加载)
*为了克服这个问题,我们使用这个方法分别加载脚本。
*/
函数invokeScript(divid){
var scriptObj=divid.getElementsByTagName(“脚本”);
var len=scriptObj.length;

对于(var i=0;我认为您正在研究ajax。当选中或取消选中按钮时,您可以调用ajax方法来更新数据库。我将这部分内容添加到我的代码中(我是通过小步完成的),但什么都没有发生。我现在测试的第一部分是单击复选框,然后我打算添加ajax调用(请参阅下面的代码)。请参阅下面的注释。您需要在我的示例中添加“.checkbox”,或者添加类“checkbox”要实现您的目标,您还需要在应用程序的后端部分处理ajax请求。但我不是jsp程序员,所以我只为您提供了部分解决方案。但与处理普通请求非常类似