PHP
Javascript并非写入文件至服务器的工具,事实上,甚至无法在服务器上运行js。因为javascript是一种客户端技术,它设计为只在浏览器上运作。
PHP是一种可在服务器上执行的脚本语言。
<?php
$filename = "blog.xml";
if (file_exists($filename)) {
// Load the blog entries from the XML file
$rawBlog = file_get_contents($filename);
}
else {
// Create an empty XML document
$rawBlog = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
$rawBlog = "<blog><title>YouCube - The Blog for Cube Puzzlers</title>";
$rawBlog = "<author>Puzzler Ruby</author><entries></entries></blog>";
}
$xml = new SimpleXmlElement($rawBlog);
// Add the new blog entry as a child node
$entry = $xml->entries->addChild("entry");
$entry->addChild("date", $_REQUEST["date"]);
$entry->addChild("body", stripslashes($_REQUEST["body"]));
if ($_REQUEST["image"] != "")
$entry->addChild("image", $_REQUEST["image"]);
// Write the entire blog to the file
$file = fopen($filename, 'w');
fwrite($file, $xml->asXML());
fclose($file);
?>
在html页面的代码如下:
<script type="text/javascript">
// Global Ajax request
var ajaxReq = new AjaxRequest();
// Add a new blog entry to an XML doc on the server using Ajax
function addBlogEntry() {
// Disable the Add button and set the status to busy
document.getElementById("add").disabled = true;
document.getElementById("status").innerHTML = "Adding...";
// Send the new blog entry data as an Ajax request
ajaxReq.send("POST", "addblogentry.php", handleRequest, "application/x-www-form-urlencoded; charset=UTF-8",
"date=" + document.getElementById("date").value + "&body=" + document.getElementById("body").value +
"&image=" + document.getElementById("image").value);
}
// Handle the Ajax request
function handleRequest() {
if (ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
// Enable the Add button and clear the status
document.getElementById("add").disabled = false;
document.getElementById("status").innerHTML = "";
// Confirm the addition of the blog entry
alert("The new blog entry was successfully added.");
}
}
// Initialize the blog entry form
function initForm() {
document.getElementById("date").value = (new Date()).shortFormat();
document.getElementById("body").focus();
}
</script>