将PHP数组传递给HTML页面。

时间:2015-03-15 18:13:00

标签: javascript php jquery html arrays

我希望能够点击按钮我想检查服务器端目录是否存在某些文件。

如果存在,我希望显示与该文件对应的复选框。

到目前为止,我已设法使用 PHP AJAX 检查文件是否存在并写入和数组:1如果文件存在,则为0如果没有。

现在......在这个阶段我需要做的是从我的PHP文件调用这个数组,或者将这个数组写入我的主HTML页面上的div。然而,当我回到它时,它导航离开我的Main.html,打开一个新页面并写上它。

最大的问题是我可以从我的 PHP_Function.php 文件在我的主html页面上编写数组。

我有以下HTML代码:

    <form action="PHP_Function.php">
        <input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />   

    </form>


    <form action="available_evidence">
        <input type="checkbox" name="vehicle" value="Bike"> Facebook<br>
        <input type="checkbox" name="vehicle" value="Car" checked> Facebook Messenger<br>
        <input type="checkbox" name="vehicle" value="Bike"> Twitter<br>
    </form>

在PHP_function.php文件中使用以下数组:

if(in_array("Facebook.xml", $dirArray)){


    $IfPresentArray[0]="1";

    }else {

    $IfPresentArray[0]="0";
}
foreach ($IfPresentArray as $value) {

    echo "$value<br />\n";
}

我对PHP和HTML非常陌生,而且我一直在用这种方式敲打我的脑袋。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您正在使用AJAX,因此您的所有通信都需要在该媒体上来回传递。简而言之,您的PHP脚本(由ajax调用的脚本)将echo JSON值(通常由json_encode($myarray)创建),然后这将在您的客户端提供给您的javascript。

对于“jquery ajax json示例”的快速google应该会为你提供一些关于它如何组合在一起的好的,有用的想法。

以下是one of those google links above的客户端 - 请注意.done部分

<script type="text/javascript">
$(document).ready(function(){
  $(':submit').on('click', function() { // This event fires when a button is clicked
    var button = $(this).val();
    $.ajax({ // ajax call starts
      url: 'serverside.php', // JQuery loads serverside.php
      data: 'button=' + $(this).val(), // Send value of the clicked button
      dataType: 'json', // Choosing a JSON datatype
    })
    .done(function(data) { // Variable data contains the data we get from serverside
      $('#wines').html(''); // Clear #wines div

      if (button == 'all') { // If clicked buttons value is all, we post every wine
        for (var i in data.red) {
          $('#wines').append('Red wine: ' + data.red[i] + '<br/>');
        }
        for (var i in data.white) {
          $('#wines').append('White wine: ' + data.white[i] + '<br/>');
        }
      }
      else if (button == 'red') { // If clicked buttons value is red, we post only red wines
        for (var i in data) {
          $('#wines').append('Red wine: ' + data[i] + '<br/>');
        }
      }
      else if (button == 'white') { // If clicked buttons value is white, we post only white wines
        for (var i in data) {
          $('#wines').append('White wine: ' + data[i] + '<br/>');
        }
      }
    });
    return false; // keeps the page from not refreshing 
  });
});
</script>

答案 1 :(得分:0)

您可以将数组存储在$_SESSION变量中,但您必须在两个页面上都使用session_start();

在您的php页面上,使用:$_SESSION['array'] = $array;然后在您的主页上通过反向检索数组:$array = $_SESSION['array'];

您现在可以在主页上使用所述数组。 要检索特定值:$value1 = $_SESSION['array'][0];

供进一步参考:

Array as session variable