简体   繁体   English

使用AJAX发布没有提交按钮的复选框列表

[英]Using AJAX to post checkbox list without submit button

I have a list of checkboxes, and want to submit the value of the checkbox when it is checked to PHP. 我有一个复选框列表,并且想要在将其选中到PHP时提交复选框的值。 I would prefer not to have a submit button, and rather post the value each time a checkbox is checked, so that the form does not refresh and clear the checked checkbox. 我不希望没有提交按钮,而宁愿每次都选中一个复选框后才发布值,这样表单就不会刷新并清除选中的复选框。 However, each time I click one of the checkboxes, nothing happens. 但是,每次我单击其中一个复选框时,都不会发生任何事情。

Here is the HTML: 这是HTML:

<form method="post" action="this.form.submit();" name="form1">
        <input type="checkbox" name="checkboxList[]" onclick="function1();" value="1">value1</input>
        <input type="checkbox" name="checkboxList[]" onclick="function1();" value="2">value2</input>
        <input type="checkbox" name="checkboxList[]" onclick="function1();" value="3">value3</input>
</form>

Here is the JQuery: 这是JQuery:

function function1() {
    var data = $("form1").serialize();
    $.ajax({
        url: "test.php", 
        type: "POST",
        async: true,
        cache: false,
        data: data, 
        success: function(data){ 
            alert(data) 
        }
    });
}

Edit: Sorry, forgot to mention that I have included the JQuery library. 编辑:对不起,忘了提到我已经包含了JQuery库。

And "test.php": 和“ test.php”:

print_r($_POST);

Instead of var data = $("form1").serialize(); 代替var data = $("form1").serialize(); you should use var data = $("[name='form1']").serialize() . 您应该使用var data = $("[name='form1']").serialize() Using a plain string like that won't find you anything. 使用这样的普通字符串不会找到任何东西。 You must specify that you want the element with the name, 'form1' 您必须指定想要名称为“ form1”的元素

您需要使用onchange事件而不是onclick事件https://api.jquery.com/change/

Try this: 尝试这个:

<form method="post" name="form1">
        <input type="checkbox" name="checkboxList[]" value="1">value1</input>
        <input type="checkbox" name="checkboxList[]" value="2">value2</input>
        <input type="checkbox" name="checkboxList[]" value="3">value3</input>
</form>

JQuery: jQuery的:

$("input[type=checkbox]").on("change", function() {
    var data = $("form1").serialize();
    $.ajax({
        url: "test.php", 
        type: "POST",
        async: true,
        cache: false,
        data: ({data: data}),
        dataType: "text", 
        success: function(data){ 
            alert(data) 
        }
    });
});

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

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