我正在javascript中构建一个数组,在其上使用JSON.stringify(),然后将隐藏输入字段的值属性设置为结果字符串。
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();
}
如果您需要更多描述,可以阅读我的评论。以下是该过程的 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>
我不知道我在电子邮件中尝试了多少不同的东西.php以获得任何类型的输出。我尝试了回显和打印,从循环和打印print_r和打印,并在"数组"内打印值,但似乎没有任何效果。这是电子邮件.php现在所处的位置:
<?php
$jsArray = json_decode($_POST['tix']);
var_dump($jsArray);
?>
我从电子邮件中得到的唯一输出.php是"NULL"(警报中不是 2 秒前)或"数组"。否则,它什么也没说,我只是得到一个空屏幕。我在这里做错了什么?是否需要使用 AJAX 来发布数据?我觉得这样不对。
问题是getElementsByName返回一个元素数组。
document.getElementsByName('tix')[0].value = (JSON.stringify(ticketInfo));
alert("The VALUE of 'tix' is: "+document.getElementsByName('tix')[0].value);