从零开始的毕设--JavaScript-Ajax(3)-POST

本文介绍如何利用PHP在服务器上执行脚本语言来处理文件操作,具体演示了通过Ajax请求将新的博客条目添加到XML文档的过程。文章详细解释了如何检查文件是否存在,如果不存在则创建一个空的XML文档,并展示了如何使用SimpleXmlElement类解析和修改XML数据,最后保存更改后的XML到文件。

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值