没有 Ajax
事实上它是有效的……只是需要修复一些细节(在 cmets 中注明):
<?php //<-- here it was "<php" fix that!
include("writemessage.php");
//Don't sent people over to writemessage, otherwise why did you include it?
echo '<form action="" method="POST">
<input type="submit" name="message" value="custom1"/>
<input type="submit" name="message" value="custom2"/>
</form>';
//Note: I changed quotes, no big deal
echo $current; //you can read $current
?>
writemessage.php:
<?php
$file = 'log.txt';
if (isset($_POST['message'])) //check if isset, also use quotes
{
// Change file to command.
$current = $_POST['message']; //again quotes
// Write the contents back to the file
file_put_contents($file, $current);
}
else
{
if (file_exists($file)) //check if file exists
{
// Open the file to get existing content
$current = file_get_contents($file);
}
else
{
// default value?
//$current = '???';
}
}
?>
阿贾克斯
我没有注意到您说“在后台提交”,这是否意味着您不想加载页面?你可以用 Ajax 做到这一点......
<?php include("writemessage.php"); ?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function _submit(value)
{
//This is the value set locally, do you want to be able to get values from other users? that is a whole level more complex
$('#current').html(value);
//Here we send the info the server via AJAX with jQuery
var ajax = $.ajax(
{
type: "POST",
url: "writemessage.php",
data: {message: value}
});
//This is the value form the server, note: it may change from another client and this will not be updated
ajax.done(function(response)
{
$('#current').html(response);
});
}
</script>
<form action="">
<input type="button" name="message" value="custom1" onclick="_submit('custom1')"/>
<input type="button" name="message" value="custom2" onclick="_submit('custom2')"/>
</form>
<span id="current"><?php echo $current; ?></span>
注意 1:我使用 jQuery 从 url http://code.jquery.com/jquery-1.10.2.min.js 选择您想要的版本并将其放置在您的服务器中。
writemessage.php:
<?php
$file = 'log.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && array_key_exists('message', $_POST))
{
$current = $_POST['message'];
file_put_contents($file, $current);
echo $current; //this is the response we send to the client
}
else
{
if (file_exists($file)) //check if file exists
{
$current = file_get_contents($file);
}
else
{
//$current = '???';
}
}
?>
注意2:你也对POST-REDIRECT-GET感兴趣。