简体   繁体   English

通过Ajax发送相同名称的多个复选框值

[英]Send same name multiple checkbox values via ajax

I have multiple checkbox input elements. 我有多个复选框输入元素。

<input type="checkbox" name="userpages[]" id="1" value="1"/>
<input type="checkbox" name="userpages[]" id="2" value="2"/>
<input type="checkbox" name="userpages[]" id="3" value="3"/>
<input type="checkbox" name="userpages[]" id="4" value="4"/>

I want to pass the value of checked element to the php script via Ajax . 我想通过Ajax将checked元素的值传递给php脚本。 I tried doing it this way - 我尝试过这种方式-

var pages = $('input[name="userpages[]"]:checked');
    $.ajax({
    type: 'POST',
    url: 'post.php',
    data: {pages: pages},
    dataType: 'json',
    success: function(data) {
        if(data.status == 1) {
            alert('Successfully posted on your Facebook pages !');
        } else if(data.status == 0) {
            alert('Error !! Please try again.');
        } else {
            alert('Unknown Error. Reloading this page now...');
            location.reload();
         }
            }
    });

and retrieved the value in php script - 并在php脚本中检索了值-

  foreach($_POST['pages'] as $page_id) {
    echo $page_id;
  }

But this didn't worked for me. 但这对我没有用。 I also tried getting the value of variable pages , when alerted it popped up 'object Object'. 我还尝试获取变量pages的值,当警告它弹出“ object Object”时。 Any help would be appreciable. 任何帮助将是可观的。 :) :)

                var checked = []
        $("input[name='userpages[]']:checked").each(function ()
        {
            checked.push(parseInt($(this).val()));
        });

The array is correct. 数组是正确的。 However, it is an array consisting of jQuery DOM elements, not the values of the inputs. 但是,它是由jQuery DOM元素组成的数组,而不是输入的值。

To get the data in the form of index => value pairs in the array, to send it by AJAX, use something like the following: 要以数组中index => value对的形式获取数据,并通过AJAX发送,请使用类似以下内容的数据:

var data = []

$('input[name="userpages[]"').each (function (index, element) {
    data[$(element).attr('id')] = $(element).val();
});
console.log(data);

Send the gathered data using the jQUery AJAX function. 使用jQUery AJAX函数发送收集的数据。

A JSFiddle: http://jsfiddle.net/LMbxC/1/ JSFiddle: http//jsfiddle.net/LMbxC/1/

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

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