[英]How to send an array of checkbox values via AJAX to PHP in the right format?
我有一组复选框,其值中包含SQL代码的位。 如果选中了它们,则应将其通过ajax发送到我的php文件中,并嵌入到我的查询中。
我只对简单的单变量ajax传输有经验,我无法通过google或stackoverflow在网上找到示例。
我的ajax电话:
$("#button1").click(function(e) {
var category_id = {};
category_id['checkboxvalue'] = $('.checkboxes:checked').serialize();
$.ajax({
type: "POST",
url: "allgemein.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttable").show().html(response);
}
});
});
我的复选框形式:
<input type="checkbox" class="checkboxes" name="checkb[]" value="MASTER.SYSTEM LIKE '%systemA'">System A</label>
<input type="checkbox" class="checkboxes" name="checkb[]" value="(MASTER.SYSTEM LIKE '%systemB' OR MASTER.SYSTEM LIKE '%systemC')">System B/C</label>
<input type="checkbox" class="checkboxes" name="checkb[]" value="MASTER.SERVICE LIKE '%serviceX%'">Service X</label>
现在在我的PHP中,我想使用像这样的数组:
$strWhere = '1=1';
if(true === isset($_POST['checkboxvalue']) && 0 < sizeof($_POST['checkboxvalue']))
{
$strWhere .= 'AND (';
foreach($_POST['checkboxvalue'] as $checkboxval)
{
$strWhere .= '"%'. $checkboxval .'%" OR ';
}
//remove last OR
$strWhere = substring($strWhere, 0, -3);
$strWhere .= ')';
}
然后将$ strWhere添加到我的SQL Where子句中。
.serialize()
为您提供一串格式编码的数据。
将对象传递给data:
将导致jQuery将表单中的值编码为表单编码数据。
由于您已经对该数据进行了编码,因此您不想对其进行重新编码 。
直接传递字符串。
data: $('.checkboxes:checked').serialize(),
如果必须通过数据发送变量,该怎么办:因为其中包含其他值?
如果您传递data
对象,那么它将通过jQuery.param传递。 您可以手动执行以下操作:
data: $('.checkboxes:checked').serialize() + "&" + jQuery.param({
some: "other",
data: "values"
}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.