【发布时间】:2016-06-27 16:26:01
【问题描述】:
我正在学习 Web 开发,但遇到了一个问题。我的表单中有四个复选框,我需要捕获选中复选框的状态。我还需要将选中的复选框 id 发送到 REST 服务,我需要对每个选中的复选框执行不同的操作。
以下是我到目前为止所做的。
<!DOCTYPE html>
<html>
<body>
<form>
<input type="checkbox" class = "checkBoxProp" id = "1" name="checkBoxProp" value="1">Graph1<br>
<input type="checkbox" class = "checkBoxProp" id = "2" name="checkBoxProp" value="2">Graph2<br>
<input type="checkbox" class = "checkBoxProp" id = "3" name="checkBoxProp" value="3">Graph3<br>
<input type="checkbox" class = "checkBoxProp" id = "4" name="checkBoxProp" value="4">Graph4<br>
<input id="btnGetResponse" type="button" value="ClickMe!"/>
</form>
<div> </div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnGetResponse").click(function()
{
var ids = []; // empty array
$('.checkBoxProp:checked').each(function() {
ids.push($(this).val()); // returning the value of the current element of all the elements selected
});
console.log(JSON.stringify(ids.join()));
$.ajax({
type: "POST",
url: "http://localhost:51349/SMS_Rest.svc/v1/usercheckboxes",
data: JSON.stringify(ids.join()) ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
sessionStorage.setItem(1, response);
window.location.href = "../backbonetest/dashboardUI.html";
},
failure: function(response)
{
alert('fail');
}
});
})
我上面所做的就是先把所有勾选的复选框都选中,然后压入一个数组,然后用join()将它转换成完整的字符串,然后再转换成JSON发送出去。
例如,如果选中第一个和第三个复选框,则发送的值是格式
"1,3" 我的休息服务。现在,由于复选框的数据完全以字符串格式发送,因此在 REST 服务中,我必须解析/拆分此字符串 (,),然后执行必要的操作。在 REST 中,我只想要类似的东西
if (firstcheckbox selected) // do something
if(secondcheckbox selected)// do something
问题:我是不是把事情复杂化了。我真的需要将所有复选框放在一个数组中吗?即使是,我是否需要使用join() 然后将其字符串化以将其发送到其余服务。我是否可以找到一种不需要在我的 REST 服务中解析/拆分发送的字符串来获取所有选中的复选框 ID 的方法。我对这一切都很陌生。请指导我。
【问题讨论】:
标签: javascript jquery json ajax rest