案例:使用xml存储数据

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <button>获取ajax信息</button>
    <h3></h3>
    <script>
      document.querySelector("button").onclick = function() {
        // 创建异步对象
        var xhr = new XMLHttpRequest();
        // 设置请求行
        xhr.open("get", "./person.php");
        // 设置请求头(get请求可以省略)
        // 注册状态改变事件
        xhr.onreadystatechange = function() {
          // 判断状态&&请求是否成功并使用数据
          if (xhr.readyState == 4 && xhr.status == 200) {
            // 返回的是xml 通过 responseText只能够获取到 字符串
            // console.log(xhr.responseText);
            // 如果返回的是 xml 使用 responseXML来获取
            var name = xhr.responseXML.querySelector("name").innerHTML;
            var age = xhr.responseXML.querySelector("age").innerHTML;
            var info = xhr.responseXML.querySelector("info").innerHTML;
            console.log(name);
            // 拼接字符串,显示在页面中
            document.querySelector("h3").innerHTML =
              name + "--" + age + "--" + info;
          }
        };
        // 发送请求
        xhr.send(null);
      };
    </script>
  </body>
</html>

PHP:

<?php
   // 告诉浏览器 返回的是xml 编码格式
   header("content-type:text/xml;charset:utf-8");
   // 接收发送过来的数据
   
    //读取xml
      // =>哪个分类中 文件分类中找
      // 参数1 文件的路径名
   $xmlString = file_get_contents('./file/person.xml');
   // 返回读取的 xml
   echo $xmlString;
?>

XML:

<root>
<name>andy</name>
<age>27</age>
<info>今天你学习了吗</info>
</root>
原文地址:https://www.cnblogs.com/qtbb/p/11873942.html