是否可以使用javascript“获取"多个XML文件?

问题描述:

我想使用handlebars.js将存储在XML Files中的数据添加到HTML视图中,但是

I want to add data that's stored in XML Files to the HTML View with handlebars.js but,

我不想添加1个url,例如:http://json.org/example.html,我想添加多个XML Files.我会为此提供任何帮助

Instead of make a GET of 1 url ex:http://json.org/example.html i will want to add multiple XML Files. I will aprreciate any help on this

提前谢谢!

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/pets-data.json');
ourRequest.onload = function() {
  if (ourRequest.status >= 200 && ourRequest.status < 400) {
    var data = JSON.parse(ourRequest.responseText);
    createHTML(data);
  } else {
    console.log("We connected to the server, but it returned an error.");
  }
};

ourRequest.onerror = function() {
  console.log("Connection error");
};

ourRequest.send();

Handlebars.registerHelper("calculateAge", function(birthYear) {
  var age = new Date().getFullYear() - birthYear;

  if (age > 0) {
    return age + " years old";
  } else {
    return "Less than a year old";
  }

});

function createHTML(petsData) {
  var rawTemplate = document.getElementById("petsTemplate").innerHTML;
  var compiledTemplate = Handlebars.compile(rawTemplate);
  var ourGeneratedHTML = compiledTemplate(petsData);

  var petsContainer = document.getElementById("pets-container");
  petsContainer.innerHTML = ourGeneratedHTML;
}

<div class="page-wrap">
  <h1>Handlebars js</h1>
  <div id="pets-container"></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>

<script id="petsTemplate" type="text/x-handlebars-template">
  {{#each pets}}
  <div class="pet">
    <div class="photo-column">
      <img src="{{photo}}">
    </div>

    <div class="info-column">
      <h2>{{name}} <span class="species">({{species}})</span></h2>

      <p>Age: {{calculateAge birthYear}}</p>

      {{#if favFoods}}
      <h4 class="headline-bar">Favorite Foods</h4>
      <ul class="favorite-foods">
        {{#each favFoods}}
        <li>{{{this}}}</li>
        {{/each}}
      </ul>
      {{/if}}

    </div>
  </div>
  {{/each}}
</script>

您需要的是一个单独的回调,仅当从各种请求中获取所需的所有数据时,该回调才被执行.为此,您将需要在正在执行的各种AJAX调用之间进行某种程度的同步.

What you need is a single callback that gets executed only when all the data you need from your various requests has been fetched. To achieve this you will need some sort of synchronization between the various AJAX calls you're doing.

Promise pattern Q库,它是该模式的几种实现之一.他们为我们完成了同步多个AJAX请求的大部分艰苦工作.

Promise pattern, the Q library, which is one of the several implementations of the pattern. They have done most of the hard work of synchronizing multiple AJAX requests for us.

我将在此处发布示例:

function xmlPromise(name) {
    return Q.promise(function (resolve, reject, notify) {
        $.ajax({
            type: "GET",
            dataType: "xml",
            async: true,
            url: name,
            contentType: "text/xml; charset=UTF-8"
        })        
       .done(function (data) {
           resolve(data);
        }).fail(function () {
            reject();
        });
    });
};

//your xml files can be stored in the promises variable
var promises = [ xmlPromise('your-xml-file-1.xml'), xmlPromise('your-xml-file-2.xml') ];
var results = [];

Q.allSettled(promises).then(function(responses) {
    results.push(responses[0].value);
    results.push(responses[1].value);
});

希望有帮助