繁体   English   中英

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

[英]How to put a PHP variable inside a html file that is being created using fwrite()?

我需要使用同一模板创建许多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变量? 还是不可能? 帮助将不胜感激! 谢谢!

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

默认情况下, <form>方法是GET ,因此$_POST['uname']什么也不会得到

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

检查$_POST["uname"]是否在您的php文件中不为空,否则,其余的php看起来还可以。

那是因为您没有将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发送uname: unameValue值,您可以在php uname: unameValue其捕获为$ _POST ['uname'] uname: unameValue

暂无
暂无

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

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