如何将PHP变量放在使用fwrite()创建的html文件中?

时间:2017-03-04 22:35:41

标签: javascript php jquery html

我需要使用相同的模板创建许多html文件。在这种情况下:

<html>
   <body>
       <h1> This is //here goes the variable// 's profile</h1>
   </body>
</html>

我需要使用登录时定义的不同变量(在本例中为“uname”)。要做到这一点,我使用的是fwrite()。 (usertest是存储所有文件的文件夹):

<?php
if(isset($_POST['action'])) {
    $uname = $_POST["uname"];
    $filecount = count(glob("usertest/*.html"));
    $filename = "user" .($filecount+1).".html";
    $myfile = fopen("usertest/$filename", "w") or die("unable to create file");
    $html = "<html><body><h1> This is" .$uname."'s profile</h1></body></html>";
    fwrite($myfile, $html);
    fclose($myfile);
?>

从这个html文件:

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script type="text/javascript" src="mango.js"></script>
</head

<body>
    <form>
        <input id="userinput" type="text" name="uname" />
       <input type="submit" class="button" value="submit" />

    </form>  
</body>
</html>

这个Jquery(mango.js):

$(document).ready(function(){
$('.button').click(function(){
     var clickBtnValue = $(this).val();
     var ajaxurl = 'ajax.php',
     data = {'action': clickBtnValue};
     $.post(ajaxurl, data, function(response) {
         alert("success!");
     });
});
});

完美创建文件名和所有内容。但是,当我打开创建的html文件时,他们只是阅读:

This is 's profile

他们完全忽略变量! 问题是,如何在html中包含此PHP变量?还是不可能? 非常感谢帮助! 谢谢!

3 个答案:

答案 0 :(得分:0)

您是否尝试过<form>替换<form method="POST">

默认情况下,<form>方法是 GET ,因此$_POST['uname']

中什么也得不到

否则,声明$uname = $_GET['uname'];

答案 1 :(得分:0)

检查php文件中$_POST["uname"]是否为空,否则,其余的php似乎没问题。

答案 2 :(得分:0)

这是因为您没有将uname发送到服务器以保存它。 js代码实际应该是:

$(document).ready(function(){
$('.button').click(function(){
     var unameValue = $('#userinput').val();
     var actionValue = $(this).val();
     var ajaxurl = 'ajax.php',
     data = {
        uname: unameValue,
        action: actionValue
     };
     $.post(ajaxurl, data, function(response) {
         alert("success!");
     });
});
});

请注意,我们现在将uname发送为uname: unameValue值,您可以在php中将其捕获为$ _POST [&#39; uname&#39;];