【问题标题】:I am losing data from a hidden input when I send it to PHP via $_POST?当我通过 $_POST 将数据发送到 PHP 时,我从隐藏的输入中丢失了数据?
【发布时间】:2012-06-13 18:34:58
【问题描述】:

我正在用 javascript 构建一个数组,在其上使用 JSON.stringify(),然后将隐藏输入字段的 value 属性设置为结果字符串。

function setSelectedArray(){

        var ticketInfo = new Array();   //creates new array for later
        var num=0;                      //num accumulates the number of the next row
        for(var i=0;i<hlRows.length;i++){
            if(hlRows[i]){  //hlRows is an array with boolean values telling me
                            //which dataArray values to set ticketInfo to
                ticketInfo[num] = dataArray[i];
                //dataArray is a pre-defined array and contains a large amount of data
                //ticketInfo is a smaller array that is gathering all data specified from hlRows
                num++;
            }
        }
        //line below sets 'tix'(hidden input field).value to the JSON version of ticketInfo
        document.getElementsByName('tix').value = (JSON.stringify(ticketInfo));

        //At this point, my alert below displays everything I want to see.
        //It looks like correct JSON to me
        alert("The VALUE of 'tix' is: "+document.getElementsByName('tix').value);

        //this submits the form that the hidden field is inside of.
        //it wouldn't go to the next page(which it does) without
        //this calling the form's action attribute correctly (i think..)
        document.forms["hiddenForm"].submit();
    }

如果您需要更多描述,可以阅读我的 cmets。这是该过程的 HTML 部分:

<!-- This button, when clicked, calls the setSelectedArray() function -->
<input class="button" type="button" id="btnContact" value="Select Tickets" onclick="setSelectedArray()" style="width:20em;float:right;"/>

<form id="hiddenForm" action="email.php" method="post">
    <input type="hidden" name="tix" value=""/> <!-- I tried this with no value specified too -->
</form>

我不知道我在 email.php 中尝试了多少不同的方法来获得任何类型的输出。 我尝试了 echos 和 print 和 print_r 并从循环中打印并在“数组”中打印值,但似乎没有任何效果。这是 email.php 现在所在的位置:

<?php
    $jsArray = json_decode($_POST['tix']);
    var_dump($jsArray);
?>

我从 email.php 得到的唯一输出是“NULL”(在警报中不是早 2 秒)或“Array”。否则,它什么也没说,我只是得到一个空屏幕。我在这里做错了什么?我需要使用 AJAX 来发布数据吗?我觉得这样不对。

【问题讨论】:

  • 建议:在您的 email.php 中对“phpinfo()”进行调试调用,然后查看发送的内容。
  • 尝试在隐藏字段上使用 ID 属性。 &lt;input type="hidden" name="tix" id="tix" value=""/&gt;
  • 注释掉表单提交并使用浏览器开发工具检查隐藏元素以查看其值是否已更改
  • 它说它正在接收“没有价值”。
  • @Lizard 你的意思是使用检查元素(我使用的是 chrome)吗?我在哪里可以看到文本字段的值?

标签: php javascript post hidden-field


【解决方案1】:

你的问题是 getElementsByName 返回一个元素数组。

document.getElementsByName('tix')[0].value = (JSON.stringify(ticketInfo));

alert("The VALUE of 'tix' is: "+document.getElementsByName('tix')[0].value);

【讨论】:

  • 我建议尽可能使用 getElementById。
  • 我一开始尝试使用 getElementById 并且发生了同样的事情。但我又试了一次,现在它让我的数据通过了。我现在在 PHP 页面上收到它。
猜你喜欢
  • 2017-01-05
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 2017-09-27
相关资源
最近更新 更多