PHP如果用户提交表单,如何更新文本

时间:2015-12-23 14:54:20

标签: javascript php html

我正在努力使用户将某些东西输入到textarea中,一旦用户提交它,内容将立即显示在id为" currentMessage"的div之内。这是php文件:



<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Message Page</title>
		<link rel="stylesheet" href="styles.css" type="text/css"/>
		
		<script type="text/javascript">
			function loadMessage(){
				document.getElementById("currentMessage").innerHTML = "<?php
					$my_file = "msg.txt";
					$handle = fopen($my_file, "r");
					$data = fread($handle, filesize($my_file));
					fclose($handle);
					echo $data;
				?>";
			}
		</script>
		
	</head>

	<body onload="loadMessage();">
		
		<?php include "header.html";?>
		<div>
			<div class="PageTitle">Messaging</div>
			<p class="Paragraph">
				Here you can send a message to the LCD display so that it may be shown when the display
				cycles through its time, temperature and status.
			</p>
			<div class="Paragraph">
				Current Message:<br>
				<p id="currentMessage" class="CodeBlock"></p>
			</div>
			<div class="SubTitle">Enter Your Message:</div>
			<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
				<textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
				<input type="submit" value="Submit Message" name="submit">
			</form>
			<?php
				if (isset($_POST['submit'])){
					$msg = $_POST["msg"];
					$my_file = "msg.txt";
					$handle = fopen($my_file, "w") or die("Cannot open file:  " . $my_file);
					fwrite($handle, $msg);
					fclose($handle);
					echo "<script>
						loadMessage();
					</script>";
				}
			?>
			
		</div>
		
	</body>
	
</html>
&#13;
&#13;
&#13; 目前,我尝试将用户的提交保存到服务器上的文件中,然后运行loadMessage()并在currentMessage div中回显结果。但是,这显然不起作用。我也是php的新手,我不知道如何指导echo的输出,或者如果没有办法更具体地说明输出文本的放置位置。

2 个答案:

答案 0 :(得分:1)

所以问题就是,你在保存文件之前加载文件的内容。 loadMessage中的php代码会在页面加载时立即执行,并且您希望在保存msg.txt文件后执行它。

如果您提交一次文本,然后尝试再次提交一些文本,则可以看到种类有效。它会显示你上次提交的内容。

虽然不应该在实际的网站上使用这种整体方法来保存信息,然后将其加载回显示,但如果你刚刚学习,那么这应该没有任何问题。

因此,要使用Javascript加载数据,您需要发出AJAX请求。

通常,大多数人在页面加载后使用 jQuery 执行AJAX请求来加载数据。

但是,为了防止您包含整个jQuery库,您可以使用vanilla Javascript异步加载msg.txt文件。这个网站http://youmightnotneedjquery.com/#request有很多有用的片段,说明如何在没有jQuery库的情况下实现相同的效果。

因此,如果您通过Javascript加载数据,那么这就是您的代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Message Page</title>
        <link rel="stylesheet" href="styles.css" type="text/css"/>

        <script type="text/javascript">
            function loadMessage(){
                console.log("Performing AJAX request!");

                var message_element = document.getElementById("currentMessage");
                var request = new XMLHttpRequest();

                // Load our msg.txt file
                request.open('GET', 'msg.txt', true);

                request.onload = function() {
                  if (request.status >= 200 && request.status < 400) {
                    // Success!
                    // Display the text we loaded.
                    resp = request.responseText;
                    message_element.innerHTML = resp;
                  } else {
                    // We reached our target server, but it returned an error
                    message_element.innerHTML = "An error occurred.";
                  }
                };

                request.onerror = function() {
                  // There was a connection error of some sort
                  message_element.innerHTML = "An error occurred.";
                };

                // Send the AJAX request (which displays the data after it has been loaded)
                request.send();
            }
        </script>

    </head>

    <body onload="loadMessage();">

        <?php include "header.html";?>
        <div>
            <div class="PageTitle">Messaging</div>
            <p class="Paragraph">
                Here you can send a message to the LCD display so that it may be shown when the display
                cycles through its time, temperature and status.
            </p>
            <div class="Paragraph">
                Current Message:<br>
                <p id="currentMessage" class="CodeBlock"></p>
            </div>
            <div class="SubTitle">Enter Your Message:</div>
            <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
                <textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
                <input type="submit" value="Submit Message" name="submit">
            </form>
            <?php
                if (isset($_POST['submit'])){
                    $msg = $_POST["msg"];
                    $my_file = "msg.txt";
                    $handle = fopen($my_file, "w") or die("Cannot open file:  " . $my_file);
                    fwrite($handle, $msg);
                    fclose($handle);
                }
            ?>

        </div>
    </body>
</html>

答案 1 :(得分:0)

我认为你遇到的问题是你正在回应没有得到评估的javascript。

尝试回应:

<script>
    (function(){
        loadMessage();
    })();
</script>

而不仅仅是

<script>
    loadMessage();
</script>

pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it