2016-05-13 94 views
-1

所以我有一個index.html下面的代碼。我想從我的GetVariable.php文件中獲取變量「variableFromMyPHPscript」到我的index.html中。從PHP腳本獲取變量爲HTML腳本?

<!doctype html> 
<html> 

<head> 
    <meta charset = "utf-8"> 
</head> 

<body> 
     <p>Random Text....</p> 
</body> 

</html> 

<script> 

     console.log(variableFromMyPHPscript); 

</script> 

這裏是我的PHP腳本(GetVariable.php),它使用JSON從我的數據庫中的值,以便它可以被存儲爲一個變量。

<script> 

    var variableFromMyPHPscript = <?php 

      $link = mysqli_connect('....', '....', '....', '....'); 
      $query = "select * from thunderDemo"; 
      $result = mysqli_query($link, $query); 

      while($row = mysqli_fetch_array($result)) 
      { 
        if($row["ThunderOrNot"] == 'Thunder') 
        { 
         echo json_encode("Thunder1"); 
        } 
      } 

       mysqli_close($link); 
      ?>; 

</script> 

那麼我將如何去獲得「variableFromMyPHPscript」的值從我的PHP文件到我的HTML文件,這樣我就可以在HTML文件中使用JavaScript使用它呢?感謝您的任何幫助!

+1

使用ajax請求獲取php變量在jquery/javascript – Poria

+0

PHP腳本不能放置在腳本標記之間,就像你做的那樣。看看這個:http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming –

+0

可能的重複[如何訪問PHP變量在JavaScript或jQuery而不是<?php echo $ variable?>](http://stackoverflow.com/questions/1808108/how-to-access-php-variables-in-javascript-or-jquery-rather-than-php -echo-VARI) –

回答

0

所以我不確定你是否完全意識到這一點,但PHP通常要麼輸出HTML(因爲PHP文件可以包含HTML),但這是一種較舊的做事方式。更好的方法是使用某種類型的MVC設計模式,其中您指定了從控制器接收其數據的視圖等。

如果您只是在尋找一種快速而髒的修復方法, HTML,上面提到AJAX的評論可能是你最好的選擇。我會用一些像jQuery的frotnend發出AJAX請求到PHP文件和HTML顯示數據/這裏是如何做到這一點的好鏈接:

Ajax tutorial for post and get

0

最簡單的方法是有的index.php文件在其中的結果JSON編碼,並將它顯示爲HTML/JS,是這樣的:

的index.php

<?php 
     $link = mysqli_connect('....', '....', '....', '....'); 
     $query = "select * from thunderDemo"; 
     $result = mysqli_query($link, $query); 
     $content = '';   

     while($row = mysqli_fetch_array($result)) 
     { 
       if($row["ThunderOrNot"] == 'Thunder') 
       { 
        $content .= "Thunder1"; 
       } 
     } 

      mysqli_close($link); 
?> 
<!doctype html> 
<html> 

<head> 
    <meta charset = "utf-8"> 
</head> 

<body> 
     <p>Random Text....</p> 
</body> 

</html> 
<script> 
     var variableFromMyPHPscript = "<?php echo json_encode($content); ?>"; 
     console.log(variableFromMyPHPscript); 

</script>