我想弄清楚选中了哪些复选框,因此尝试了以下代码:
$('.feature input[type="checkbox"').serialize();
这是我的HTML外观:
<div class="feature">
<h2>Features</h2>
<label><input class="custom_css" checked="" type="checkbox" name="feature[]"> Custom CSS (style.css)</label>
<label><input class="custom_js" checked="" type="checkbox" name="feature[]"> Custom Javascript (script.js)</label>
<label><input class="modernizr" type="checkbox" name="feature[]"> Modernizr</label>
<label><input class="google_maps" type="checkbox" name="feature[]"> Google Maps</label>
<label><input class="custom_api" type="checkbox" name="feature[]"> Custom API</label>
<label><input class="font_awesome" type="checkbox" name="feature[]"> Font Awesome</label>
</div>
这是我得到的输出:
array(1){[“” var_sent_via_ajax“] =>字符串(67)
“ feature%5B%5D = on&feature%5B%5D = on&feature%5B%5D = on&feature%5B%5D = on”
}
现在,我怎么知道已经检查了哪一个?符号%5B%5D是什么意思?
最佳答案
关于:%5B%5D
答:它们只是“ []”的原始http编码值(序列化函数的结果)。
服务器解析时,它将转换为[]并发送到威胁它的应用程序作为数组。
关于您为什么变得虚假的原因:“ feature%5B%5D = on&feature%5B%5D = on ...”字符串
答:您忘记为每个复选框提供一个值参数,那么它们将类似于:“ feature%5B%5D = custom_css&feature%5B%5D = custom_js ...”
我已经写了解决方案。
以这个工作示例为例,在服务器端应用程序上处理请求的“功能”参数,就像字符串一样,并用“,”将其缩小(PHP:$features = explode(',', $_POST['features']
);
$(function() {
$('#getFeatures').click(function() {
var features = [];
$('.feature input[type="checkbox"]:checked').each(function() {
features.push($(this).val());
});
$('#selectedFeatures').html(features.join(','));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feature">
<h2>Features</h2>
<label><input class="custom_css" checked="" type="checkbox" name="feature[]" value="custom_css"> Custom CSS (style.css)</label>
<label><input class="custom_js" checked="" type="checkbox" name="feature[]" value="custom_js"> Custom Javascript (script.js)</label>
<label><input class="modernizr" type="checkbox" name="feature[]" value="modernizr"> Modernizr</label>
<label><input class="google_maps" type="checkbox" name="feature[]" value="google_maps"> Google Maps</label>
<label><input class="custom_api" type="checkbox" name="feature[]" value="custom_api"> Custom API</label>
<label><input class="font_awesome" type="checkbox" name="feature[]" value="font_awesome"> Font Awesome</label>
</div>
<button id="getFeatures">GET FEATURES</button>
<div id="selectedFeatures"></div>
关于javascript - 获取所有选中复选框的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38185847/