[英]Passing javascript array via POST to PHP does not working
我需要通過POST將javascript數組傳遞給PHP文件。
我試圖簡化我的原始業務,試圖解釋我的麻煩...
這是我的第一個PHP文件,在其中聲明了一個javascript數組,並將每個元素設置為1值(我知道這不是什么好事,但這沒關系,僅是為了解釋..)
<?php
echo '<form action="testPhp-2.php" method="POST" target="testPhp-2">';
echo '<script type="text/javascript">';
echo 'var arr_selections = [];';
echo 'for(i=0; i < 10; i++)';
echo ' {';
echo ' arr_selections[i] = 1';
echo ' }';
echo 'arr_selections_json = JSON.stringify(arr_selections);';
echo 'alert (arr_selections[2]);';
echo 'document.write("<br/>");';
echo ' ';
// echo 'document.write("<input type="hidden" />");';
echo 'document.write("<input type=\"hidden\" name=\"arr_selections_json\" value=\"arr_selections_json\" />");';
echo ' ';
echo '</script>';
echo ' <input type="submit" value="Controlla">';
echo ' </form>';
?>
....這是testPhp-2文件的代碼...
<?php
if(isset($_POST['arr_selections_json']))
{
echo "OK, array exist !! ";
echo '</br>';
echo '</br>';
$arr_selections = json_decode($_POST['arr_selections_json'], true);
echo $arr_selections[0];
}
else {
echo "NO; array does not exist !! ";
echo '</br>';
echo '</br>';
}
?>
現在,如果您嘗試執行代碼,您將看到OK,數組存在! 消息,但沒有顯示關於回顯$ arr_selections [0]的數組值; testPhp-2.php文件中的代碼行。
任何建議將不勝感激! 先感謝您!
切薩雷
問題是您正在將輸入值設置為文本字符串"arr_selections_json"
而不是該變量的內容。
更改
echo 'document.write("... value=\"arr_selections_json\" />");';
至
echo 'document.write("... value=\""+arr_selections_json+"\" />");';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.