Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

javascript - Displaying data from XML file using AJAX

I need to make a communicator using AJAX and XML file. I've already done function to download the data from the form and send it via AJAX to the server(XML file). The code below is in JavaScript.

function send(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 20) {
        download(this);
    }
    xhttp.open("GET", "file.xml", true);
    xhttp.send();
}

But I don't know how to make function that is sending an AJAX request to the server to download new messages and displaying them in the communicator.

function download(xml){
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("author");
}

I am downloading the data from the input in HTML and this is the way I save it to the XML file.

<?php

$author = $_GET["author"];
$message = $_GET["message"];
$file = 'file.xml';

if (!empty($author) && !empty($message)) {
    $xml = simplexml_load_file($file);
    $entry = $xml->addChild("entry");
    
    $sxe = simplexml_import_dom($xml);
    $sxe ->addChild("author", $author);
    $sxe ->addChild("message", $message);
    
    $xml->asXml($file);
}
header('location: index.html');
?>

My XML file looks like this after the send function.

<?xml version="1.0"?>
<entry>
  <author>gnow</author>
  <message>BAKDA</message>
<entry/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

somthing like that...

function downloadXML()
  {
  let xmlhttp = new XMLHttpRequest() 
  
  xmlhttp.onreadystatechange = function()
    {
    if (this.readyState===4)  /* DONE */
      {  
      if (this.status!=200)  /* not LOADING */
        {
        console.warn("Error %d on load %s !", this.status, 'fileName.xml' )
        }
      else
        {
        let xmlDoc  = this.responseXML
          , author  = xmlDoc.querySelector('entry author').textContent
          , message = xmlDoc.querySelector('entry message').textContent
        }
      }
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...