繁体   English   中英

如何通过ajax将带有复选框数据的数组发送到PHP脚本

[英]how to send an array with checkbox data via ajax to a php script

还有另一个问题,与ajax有关,以及如何从复选框表单发送数据而无需任何页面重新加载/重定向,我有以下代码,这是标记:

 <html>
   <head>
      <title>guild</title>
   </head>
   <body>
      <div id="dive">
         <form method="post" action="">
            <input type="checkbox" name="userList[]" value="together" />together<br />
            <input type="checkbox" name="userList[]" value="we" />we<br />
            <input type="checkbox" name="userList[]" value="made" />made<br />
            <input type="checkbox" name="userList[]" value="it" />it<br />
            <input type="submit" id="submit" value="yeah we did it!" />
         </form>
      </div>
      and here's the jquery:
      <script type="text/javascript" src="jquery-1.8.0.min (1).js"></script>
      <script type="text/javascript">
         $(document).ready(function(){
         //when the button is clicked
         $("#submit").click(function(){
         //put the checked data into an array
         var userList= $('#dive input[type=checkbox]:checked').serializeArray();
         //send the data without page reload/refresh/redirect
         $.post("guild.php", {userList: userList},function(userList)
         {
         });
         });
         });
      </script>
   </body>
</html>

因此,应该将检查后的数据发送到php文件,然后将其写入文件,这是脚本:

<?php
//get sent data
$userList=$_POST['userList'];
//open file to be written to
$fp=fopen("guild.html", 'a');
//write data into file
for($i=0;$i<sizeof($userList);$i++) 
{
fwrite($fp, "<div class='gn'>."userList[$i]"."<br>"."</div>");
}
//close file
fclose($fp);
?>

我知道这是一个非常简单的问题,但是即使阅读了其他答案,我也无法使其正常工作。 我需要将检查后的数据以数组而不是字符串的形式发送。 因此,我将如何更改jquery部分以使其正常工作?感谢您的帮助,我是一个极端的初学者!

根据jQuery post文档 ,您应该像这样发送post数据数组:

$.post("guild.php", { "userList[]": userList }...

我使用该脚本,并且收到以下消息:

Array ( [0] => [object Object] [1] => [object Object] )

我使用以下代码:

function add_apartament ()
    {
var vedere= $('#vedere input[type=checkbox]:checked').serializeArray();
        $.ajax({
            type: "POST",
            url: "inc/ajax/add_apartament_action.php",
            data: { 
                    'vedere[]':vedere
                  },
            success: function (msg) {

                $("#action").html(msg);
            },
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            }
        });


    }

和PHP ...

<?php

print_r($_POST['vedere']);

?>

暂无
暂无

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

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