为什么我无法在我的php5代码中获取javascript值?

时间:2017-07-21 11:19:38

标签: javascript php php-5.2

我有这段代码:

<?php       $html=file_get_contents('testmaker_html.html');
        echo $html;
?>



<script type="text/javascript">


    document.getElementById('save_finaly_TEST').addEventListener("click", function(){
        cover = document.getElementById('cover').value;
        keywords = document.getElementById('keywords').value.split(",");

        notificationAboutElement = "Ok!";
        notifyMe(notificationAboutElement);
      html_saver();

    <?php $test_html = "<script>document.write(html)</script>"?>   


    }); 

</script>
<?php 
        $new_test = rand().".html";
        $myfile = fopen($new_test, "w") or die("Unable to create file!");
        write($myfile, $test_html)  or die("Can't write to file");
        fclose($myfile)  or die("Can't close the file!");
        echo $new_test;
?>


<script type="text/javascript">
    console.log("$test_html: " + <?php echo $test_html; ?>);
    console.log("$new_test: " + <?php echo $new_test; ?>);
</script> 

为什么$test_html为空?我知道php和javascript不在同一台服务器上,但这种方法可以为很多人多次获取值。比这可能有什么不妥?

2 个答案:

答案 0 :(得分:0)

PHP在服务器上运行,Javascript在客户端上运行。所以当Javascript运行时,PHP已经运行了。

<?php 
    $new_test = rand().".html";
    $myfile = fopen($new_test, "w") or die("Unable to create file!");
    fwrite($myfile, $test_html)  or die("Can't write to file");
    fclose($myfile)  or die("Can't close the file!");
    echo $new_test;
?>
<script>
    var new_test = "<?php echo $new_test; ?>";

    console.log("$new_test: " + new_test);
</script>

这里您将获取文件的内容,并对其进行JSON编码,以便将其作为有效的Javascript对象发送到客户端。看一下view source,看看我的意思。

对于其他情况:

  • 如果您希望客户端向服务器提交内容,请创建一个POST API
  • 如果您只想在页面上显示来自Javascript的内容,请使用Javascript

答案 1 :(得分:0)

试试这个

您必须仅使用fwrite而非write进行文件写入

<?php       
        $html=file_get_contents('testmaker_html.html');
        echo $html;
?>
<script type="text/javascript">
    document.getElementById('save_finaly_TEST').addEventListener("click", function(){
        cover = document.getElementById('cover').value;
        keywords = document.getElementById('keywords').value.split(",");

        notificationAboutElement = "Ok!";
        notifyMe(notificationAboutElement);
      html_saver();

    <?php $test_html = "<script>document.write(html)</script>"?>   
    }); 
</script>
<?php 
        $new_test = rand().".html";
        $myfile = fopen($new_test, "w") or die("Unable to create file!");
        fwrite($myfile, $test_html)  or die("Can't write to file");
        fclose($myfile)  or die("Can't close the file!");
        echo $new_test;
?>
<script type="text/javascript">
    console.log("$test_html: " + <?php echo $test_html; ?>);
    console.log("$new_test: " + <?php echo $new_test; ?>);
</script>