简体   繁体   English

将 PHP 数组发送到 Javascript

[英]Sending PHP array to Javascript

I have created an array in PHP.我在 PHP 中创建了一个数组。 And I need to get that array into a javascript function.我需要将该数组放入 javascript function。 This is what I have tried.这是我尝试过的。

$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
    $ValidatinArray[$J] = $RowVal['Validation_Type'];
    $J++;
}

And This is my javascript code.这是我的 javascript 代码。

$(document).ready(function() {
    $("form").submit(function(){
    var P= <?php echo json_encode($ValidatinArray); ?>;
        var O = P.length;
        alert(O);
        return false;
    });
}); 

But this gives me an error like this但这给了我这样的错误

 SyntaxError: syntax error
 var P= <br />

Isn't it possible to get the array in this way.是不是可以通过这种方式获取数组。 Please someone help me.请有人帮助我。

UPDATE: This is the final out put of my error message更新:这是我的错误消息的最终输出

<script>
    $(document).ready(function() {
        $("form").submit(function(){
            alert('AAAAAAAAAAAAAAAAAAA');
            var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
            var Data = document.getElementsByName("DataInputValue[]");
            var A = IDsOfTheColumns.length;
            alert(A);
            <br />
            <b>Notice</b>:  Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
            var P = null;   return false;
        });
    });
</script>

The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code.问题是,变量$ValidatinArray在文件中不可用,它打印了 javascript 代码。 Maybe this manual page helps you:也许这个手册页可以帮助你:

http://www.php.net/manual/en/language.variables.scope.php http://www.php.net/manual/en/language.variables.scope.php

Your tag is coming from the form that you are submitting.您的标签来自您提交的表单。 check what your form data is before you encode it to verify the output.在编码之前检查表单数据是什么以验证输出。 you can use console.log($("form));你可以使用 console.log($("form));

Also using form is not a good idea since if you have more than one form and form is a global name.同样使用表单也不是一个好主意,因为如果您有多个表单并且表单是一个全局名称。 For forms you should give it a unique form name like "myForm" so that you can target that specific form.对于表单,您应该为其指定一个唯一的表单名称,例如“myForm”,以便您可以定位该特定表单。

Hope this helps希望这有帮助

Sorry for the late response...Try rewriting your document.ready as:抱歉回复晚了...尝试将您的文档重写为:

$(document).ready(function() {
    $("form").submit(function(){
    var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
        var O = P.length;
        alert(O);
        return false;
    });
});

Try this:试试这个:

<?php


    echo   ' <script>
             $(document).ready(function() {
                                $("form").submit(function(){
                                var P= '. json_encode($ValidatinArray) . ';
                               var O=P.length;
                                 alert(O);
                               return false;
                          });
                   }); 
               </script>';

?>

What you do is simply echo the js using php.您所做的只是使用 php 回显 js。

first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".首先,我建议您验证变量 $ValidatinArray 是否存在,并且它是否被正确传递到您正在执行“echo”的文件。

the error you show indicates that from the beginning the variable that contains the array does not exist.您显示的错误表明从一开始包含该数组的变量不存在。 if the SQL query is inside a php function check that you are returning the variable.如果 SQL 查询在 php function 内,请检查您是否正在返回变量。 example例子

<?php 

  function GetData(){
   // ... here is the code to get the information from the database ...
   return $ValidatinArray;
  
  }

  $ValidatinArray = GetData();
?>

once you have validated that this array exists we can now see the problem of passing the data to JavaScript:一旦您确认此数组存在,我们现在可以看到将数据传递给 JavaScript 的问题:

It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil: It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:

// ... php file code
?>
    <script>
      $(document).ready(function() {
       $("form").submit(function(){

       // you can use any of the two methods that I leave you here
       // Using only json_enconde
       var P= <?= json_encode($ValidatinArray) ?>;

       // Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
       var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');

       var O = P.length;
       alert(O);
       return false;
      });
     });
    </script>

In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:如果在打开页面时执行 php 文件,并且包含 JavaScript 中的 function 的文件位于另一个文件中:

You can generate a "global" JavaScript variable from the php code as follows您可以从 php 代码生成“全局” JavaScript 变量,如下所示

 // ... code php file
 ?>
 <script>
     window.variablename = <?= json_encode($ValidatinArray) ?>
 </script>
 <?php

inside your JS file you can receive the array like this在您的 JS 文件中,您可以像这样接收数组

$(document).ready(function() {
    $("form").submit(function(){
       var P= window.variablename ;
       var O = P.length;
       alert(O);
       return false;
    });
  });

PD: using <?= is equivalent to using echo PD:使用 <?= 等同于使用 echo

In php json_encode the array like this:在 php json_encode 中,数组是这样的:

$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";

and in javascript:在 javascript 中:

$(document).ready(function() {
    $("form").submit(function(){
    <?php echo $inlinejs; ?>
    console.log(validatinArray);
    });
}); 

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

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