我想弄清楚哪些复选框被选中,所以我尝试了这段代码:
$('.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"]=> string(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...
string
答:您忘记给每个复选框一个值参数,那么它们将像:feature%5B%5D=custom_css&feature%5B%5D=custom_js...
我写了解决方案。
以这个工作示例为例,像字符串一样处理服务器端应用程序请求的“功能”参数,并通过 ,
缩小它(php: $features = explode(',', $_POST[ '功能']
);
$(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/