我在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();
}
如果您需要更多说明,可以阅读我的评论。以下是该过程的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中尝试了多少不同的东西来获得任何类型的输出。 我尝试了回声和print和print_r并从循环打印并在“数组”中打印值,但似乎没有任何效果。这是email.php现在的位置:
<?php
$jsArray = json_decode($_POST['tix']);
var_dump($jsArray);
?>
我从email.php获得的唯一输出是“NULL”(警报中提前2秒)或“Array”。否则,它什么也没说,我只是得到一个空屏幕。我在这做错了什么?我是否需要使用AJAX发布数据?我觉得这样不对。
答案 0 :(得分:5)
你的问题是getElementsByName返回一个元素数组。
document.getElementsByName('tix')[0].value = (JSON.stringify(ticketInfo));
alert("The VALUE of 'tix' is: "+document.getElementsByName('tix')[0].value);