0

我正在尝试创建一组复选框,我可以检查并通过 ajax 发送。

理想情况下,我希望通过 ajax 将几条信息发送到 php 脚本,the checkbox that has been checked以及id

id基于 URL,所以我可以使用$_GET['id'].

因此,如果用户选中了这两个框,则需要发送到 php 脚本的值将是:

53 57 1- 此值是 URL 中的值。

到目前为止,我有以下内容:

<input type="checkbox" name="test[]" value="53" id="part_shipping" />
<input type="checkbox" name="test[]" value="57" id="part_shipping" />
<input name="confirm" type="button" value="confirm" />

<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">

$('input[type=button]').click( function() {
   $(":checked").each(function() {
   var value = $(this).val();
         id = 'id:1';
         data = 'shipping:' + value;
         console.log(data);
   });
    $.post("ajax.php", data);   
});

</script>

如何在数据中附加 id,使其显示为: shipping:53 shipping:57 id:1

4

1 回答 1

0

如果<input>标签不在 a<form>中,则添加一个:

<form id="myForm">
    ...
    <input type="checkbox" name="test[]" value="53" id="part_shipping" />
    <input type="checkbox" name="test[]" value="57" id="part_shipping" />
    <input name="confirm" type="button" value="confirm" />
    ...
</form>

现在,您可以使用 jQuery.serialize()编写格式为“name1=value1&name2=value2&name3=value3”等的数据字符串,其中名称与 HTML 中给出的名称相同:

$(function() {
    $('input[type=button]').click( function() {
        $.post("ajax.php", $("#myForm").serialize());   
    });
});

复选框只有在被选中时才会出现在序列化表单中。而且我认为我说按钮不会包含在序列化中是对的。

这样做的好处是脚本可以响应表单中的设计更改。如果添加或删除字段,则不需要更改 javascript。

于 2012-06-30T10:15:36.477 回答