简体   繁体   English

如何通过AJAX以正确的格式将复选框值数组发送到PHP?

[英]How to send an array of checkbox values via AJAX to PHP in the right format?

I have a set of checkboxes, that contain bits of SQL Code in their value. 我有一组复选框,其值中包含SQL代码的位。 If they're checked, they should be send via ajax to my php file and be embedded in my query. 如果选中了它们,则应将其通过ajax发送到我的php文件中,并嵌入到我的查询中。

I'm only experienced with simple single variable ajax transfer and i just can't make the examples I find online via google or on stackoverflow to work. 我只对简单的单变量ajax传输有经验,我无法通过google或stackoverflow在网上找到示例。

My ajax call: 我的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);
        }
    });
});

My checkbox form: 我的复选框形式:

<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>

Now in my php I want to use the array like this: 现在在我的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 .= ')';
    }

Then add $strWhere to my SQL Where clause. 然后将$ strWhere添加到我的SQL Where子句中。

.serialize() gives you a string of form encoded data. .serialize()为您提供一串格式编码的数据。

Passing an object to data: will cause jQuery to encode the values in the form as form encoded data. 将对象传递给data:将导致jQuery将表单中的值编码为表单编码数据。

Since you have already encoded that data, you don't want to reencode it. 由于您已经对该数据进行编码,因此您不想对其进行重新编码

Pass the string directly. 直接传递字符串。

data: $('.checkboxes:checked').serialize(),

What can I do, if I have to send a variable via data: because I have other values in it? 如果必须通过数据发送变量,该怎么办:因为其中包含其他值?

If you pass data an object then it gets passed through jQuery.param. 如果您传递data对象,那么它将通过jQuery.param传递。 You can do that manually: 您可以手动执行以下操作:

data: $('.checkboxes:checked').serialize() + "&" + jQuery.param({
  some: "other",
  data: "values"
}),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM