javascript 如何通过 POST 类型通过 html 表单发送 PHP 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11684274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:00:31  来源:igfitidea点击:

How to send PHP array by html form by POST type

phpjavascripthtmlarrayspost

提问by Vivek

I am trying to send PHP array by html form by POST. The code which I am using is below:

我正在尝试通过 POST 以 html 形式发送 PHP 数组。我正在使用的代码如下:

<?php
    $content = array('111', '222' );
?>

    <html>
    <head>
    <title>PAGE TITLE</title>
    </head>
        <body>
            <form name="downloadexcel" action="downloadexcel.php" method="post">
                <input type="text" name="data" value="<?php echo $content; ?>"/>
                <a href="javascript: submitform()">Download</a>
            </form>
            <script type="text/javascript">
                function submitform()
                {
                  document.downloadexcel.submit();
                }
            </script>
        </body>
    </html>

How can I send an PHP array by html form?

如何通过 html 表单发送 PHP 数组?

Any web link or source code would be appreciated.

任何网络链接或源代码将不胜感激。

回答by Ajay Kadyan

<?php
$content = array('111', '222' );
?>

<html>
<head>
<title>PAGE TITLE</title>
</head>
    <body>
        <form name="downloadexcel" action="downloadexcel.php" method="post">
            <?php foreach($content as $c) { ?>
               <input type="text" name="data[]" value="<?php echo $c; ?>"/>
            <?php }  ?>
            <a href="javascript: submitform()">Download</a>
        </form>
        <script type="text/javascript">
            function submitform()
            {
              document.downloadexcel.submit();
            }
        </script>
    </body>
</html>

回答by Paul T. Rawkeen

You can't send array like this. It will return Array. You can do it this way

你不能像这样发送数组。它将返回Array。你可以这样做

<form name="downloadexcel" action="downloadexcel.php" method="post">

<?php foreach ($content as $item): ?>
    <input type="text" name="data[]" value="<?php echo $item; ?>"/>
<?php endforeach ?>

<a href="javascript: submitform()">Download</a>
</form>

This variant is the most elegant to use in templates or anywhere in the code. HTMLwill be easily validated by IDEand code assistwill be also available.

这种变体在模板或代码中的任何地方使用是最优雅的。HTML将很容易被验证IDE并且code assist也将可用。

回答by JK.

Here's is an simple example:

这是一个简单的例子:

$content = array('111', '222');

foreach($content as $c)
{
    echo "<input name='arr[]' value='{$c}'>";
}

You could alternatively use serializeand unserializeto send the values.

您也可以使用序列化和反序列化来发送值。