【问题标题】:how to checkbox value stored array when click checkbox using ajax使用ajax单击复选框时如何复选框值存储的数组
【发布时间】:2017-02-16 01:23:02
【问题描述】:

HTML

<input type="checkbox" name=options[cid]" value='1'     
onChange="chkdeptCount(this.value)" class="test">    
<input type="checkbox" name=options[cid]" value='2'     
onChange="chkdeptCount(this.value)" class="test">

jquery:

function chkdeptCount(val){    
$.ajax({ url: '../ajax/AjaxCall.php',
    data: {Action:'IMPLODEARRAY',arrVal: val},
    type: 'post',
    success: function(output) {
   alert(output);
    $('.result').html(output);
    }
    });

}

PHP:

if($_POST['Action']=='IMPLODEARRAY'){       
    $arr_val[] = $_POST['arrVal'];      
    print_r($arr_val);
}

当我运行此代码时,不返回数组值。它返回一个值 为什么?

【问题讨论】:

  • 请添加正确的代码,我看不懂。
  • 你已经尝试过什么来达到预期的效果?为什么它不起作用?
  • 输出为 1 然后警报 2
  • name=options[cid]" 缺少报价,两个复选框都有 onchange 事件,并且您正在使用 this 获取当前值
  • @shubhamkhatri 您不应该更改基本示例。如前所述,name="options[cid]" 不在 OP 中。是name=options[cid]" 这可能是代码的问题。您不应该编辑实际的脚本,只编辑格式。

标签: php jquery html css ajax


【解决方案1】:

请注意,您在这里缺少引用 name=options[cid]"

你正在使用 onChange="chkdeptCount(this.value)" 事件和当前值 this,这一次只会返回一个值。

这是非常基本的示例:

HTML:

<form method="post" id="formID" action="">
<input type="hidden" name="Action" value="IMPLODEARRAY">
<input type="checkbox" name="options[cid]" value='1' class="test">
<input type="checkbox" name="options[cid]" value='2' class="test">
<input type="submit" name="submit" value="Submit" id="SubmitButton">
</form>

AJAX:

<script type="text/javascript">
$(document).ready(function(){
  $("#SubmitButton").click(function(){ // when submit button press
    var data = $("#formID").serialize(); // get all form input in serialize()
    $.ajax({
        url: YourURL, // add your url here
        type: "POST", // your method
        data: data, // your form data
        dataType: "json",  // you can use json/html type
        success: function(response) {
          console.log(response); // your response
        },
        beforeSend: function()
        {
            // if you want to display any loading message
        }
    });  // JQUERY Native Ajax End
    return false;
  });
});
</script>

PHP:

<?php
if(count($_POST) > 0){ // if you have some value in AJAX request
  if($_POST['Action'] == 'IMPLODEARRAY'){ // your condition
    print_r($_POST['options']); // get all checkbox value.
  }
}
?>

更多的例子可以帮助你理解,你可以使用:Submitting HTML form using Jquery AJAX | jQuery AJAX submit form

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2011-05-24
    相关资源
    最近更新 更多