简体   繁体   English

通过POST将JavaScript数组传递给PHP无法正常工作

[英]Passing javascript array via POST to PHP does not working

I need to pass a javascript array, via POST, to a PHP file. 我需要通过POST将javascript数组传递给PHP文件。

I've tried to semplify my original business trying to explain my troubles ... 我试图简化我的原始业务,试图解释我的麻烦...

This is my first PHP file, in which I declare a javascript array and I set each element to 1 value (not a great business I know, but it doesn't matter, it's only to explain ....) 这是我的第一个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>';


?>

.... and here you are the code of testPhp-2 file ... ....这是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>';
  }

?>

Now, if you try to execute the code you'll see the OK, array exist !! 现在,如果您尝试执行代码,您将看到OK,数组存在! message but no array value is printed about the echo $arr_selections[0]; 消息,但没有显示关于回显$ arr_selections [0]的数组值 line of code in testPhp-2.php file. testPhp-2.php文件中的代码行。

Any suggestion will be appreciated! 任何建议将不胜感激! Thank you in advance! 先感谢您!

Cesare 切萨雷

Problem is that you're setting the value of the input to the litteral string "arr_selections_json" instead of to the contents of that variable. 问题是您正在将输入值设置为文本字符串"arr_selections_json"而不是该变量的内容。

Change 更改

echo 'document.write("... value=\"arr_selections_json\" />");';

To

echo 'document.write("... value=\""+arr_selections_json+"\" />");'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM