Возврат AJAX в документ HTML не определен - PullRequest
0 голосов
/ 27 сентября 2018

У меня есть следующий XML-документ

<?xml version="1.0" ?>
<result searchKeyword="Mathematics">

  <video>
    <title>Chaos Game</title>
    <channel>Numberphile</channel>
    <view>428K</view>
    <link>http://www.youtube.com/watch?v=kbKtFN71Lfs</link> 
    <image>http://i.ytimg.com/vi/kbKtFN71Lfs/0.jpg</image> 
    <length>8:38</length>
  </video> 

  <video>
    <title>Australian Story: Meet Eddie Woo, the maths teacher you wish you&apos;d had in high school</title>
    <channel>ABC News (Australia)</channel>
    <view>223K</view>
    <link>http://www.youtube.com/watch?v=SjIHB8WzJek</link> 
    <image>http://i.ytimg.com/vi/SjIHB8WzJek/0.jpg</image> 
    <length>28:08</length>
  </video> 

  <video>
    <title>Ham Sandwich Problem</title>
    <channel>Numberphile</channel>
    <view>557K</view>
    <link>http://www.youtube.com/watch?v=YCXmUi56rao</link> 
    <image>http://i.ytimg.com/vi/YCXmUi56rao/0.jpg</image> 
    <length>5:53</length>
  </video> 

  <video>
    <title>Magic Square Party Trick</title>
    <channel>Numberphile</channel>
    <view>312K</view>
    <link>http://www.youtube.com/watch?v=aQxCnmhqZko</link> 
    <image>http://i.ytimg.com/vi/aQxCnmhqZko/0.jpg</image> 
    <length>3:57</length>
  </video> 

  <video>
    <title>The 8 Queen Problem</title>
    <channel>Numberphile</channel>
    <view>909K</view>
    <link>http://www.youtube.com/watch?v=jPcBU0Z2Hj8</link> 
    <image>http://i.ytimg.com/vi/jPcBU0Z2Hj8/0.jpg</image> 
    <length>7:03</length>
  </video> 

</result>

Я создал этот HTML-файл, в котором есть вызов AJAX для получения XML-файла, но он возвращает все значения как «неопределенные»

<html>
<head>
    <title>A7-Question2</title>

    <script>
        function getSearch()
        {
            // create an XMLHttpRequest
            var xhttp = new XMLHttpRequest();

            //create a handler for the readyState change
            xhttp.onreadystatechange = function() {
                 readyStateChangeHandler(xhttp);
            };

          //get XML file by making async call
          xhttp.open("GET", "A7.xml", true);
          xhttp.send();
        }

        // handler for the readyState change
        function readyStateChangeHandler(xhttp){
          if (xhttp.readyState == 4){
            // readyState = 4 means DONE

            if(xhttp.status == 200){
              // status = 200 means OK

              handleStatusSuccess(xhttp);
            }else{
              // status is NOT OK

              handleStatusFailure(xhttp);
            }
          }
        }

        // XMLHttpRequest failed
        function handleStatusFailure(xhttp){

          // display error message

          var displayDiv = document.getElementById("display");

          displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
        }

        // XMLHttpRequest success
        function handleStatusSuccess(xhttp){

          var xml = xhttp.responseXML;

          // print XML on the console
          console.log(xml);

          // parse the XML into an object
          var searchResult = parseXML(xml);

          // print object on the console
          console.log(searchResult);

          // display the object on the page
          display(searchResult);
        }

        // parse the XML into an object
        function parseXML(xml){

         var resultElement = xml.getElementsByTagName("result")[0];

         //create a receipt object to hold the information in the xml file
         var searchResult = {};
         searchResult.searchKeyword= resultElement.getAttribute("searchKeyword");

         var videoElements = xml.getElementsByTagName("video");

         //create an array to hold the items
         searchResult.videoArray = [];

         for(var i=0; i< videoElements.length; i++){
             var video = {};
             video.title = videoElements[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
             video.channel = Number(videoElements[i].getElementsByTagName("channel")[0].childNodes[0].nodeValue);
             video.view = Number(videoElements[i].getElementsByTagName("view")[0].childNodes[0].nodeValue);
             video.link = Number(videoElements[i].getElementsByTagName("link")[0].childNodes[0].nodeValue);
             video.image = Number(videoElements[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
             searchResult.videoArray.push(video);
        };
          return searchResult;
        }

        // display the searcg result object on the page
        function display(searchResult){

            var html = "<p>searchKeyword: Mathematics</p>";
            for(var i=0; i<searchResult.videoArray.length; i++){
            var video = searchResult.videoArray[i];
            html += "title: " + searchResult.title + "<br/>";
            html += "channel: " + searchResult.channel + "<br/>";
            html += "view: " +  searchResult.view + "<br/>";
            html += "link: " +  searchResult.link + "<br/>";
            html += "image: " +  searchResult.image + "<br/>";
            html += "length: " +  searchResult.length + "<br/>";
            }

            var displayDiv = document.getElementById("display");

            displayDiv.innerHTML = html;
        }
    </script>
</head>
<body>
    <button onclick="getSearch()">Get Search Result</button>
    <div id="display"></div>
</body>
</html>

Проблема с моей функцией успеха?Возвращается ли значение null, потому что он не вернул все значения или что-то из-за того, как работает AJAX?

Спасибо огромное за любую помощь

1 Ответ

0 голосов
/ 27 сентября 2018

Требуется много кода и рабочий фрагмент не может быть создан, потому что мы не можем поместить XML-файл здесь.

Этот ответ предполагает, что ваш ответ от XMLHttpRequest имеет значение null, и проблема не заключается ни в одной из ваших функций синтаксического анализа.

Также кажется, что вы слишком усложнили процесс запроса, передав его многим функциям, когда он сам по себе довольно прост.

Вот пример, который я сделал локально, чтобы правильно записать XML в консоль:

<!doctype html>
<html>
<head>
    <title>A7-Questions2</title>
</head>
<body>

    <script>

        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function () {

            if (xhttp.readyState == 4 && xhttp.status == 200) {

                var xml = xhttp.responseXML;

                // Logs just fine for me. You can do your parsing here.
                console.log(xml);

            }

        };

        xhttp.onerror = function() {

            // Display error message.
            var displayDiv = document.getElementById('display');

            displayDiv.textContent = 'XMLHttpRequest failed status: ' + xhttp.status;

        };

        xhttp.open('GET', './path/to/xml.xml');
        xhttp.send();

    </script>

</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...