It's possible to 'GET' multiple XML fi

2019-07-17 19:20发布

问题:

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

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

Thanks in advance!

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>

回答1:

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, 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.

I will post an example here:

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);
});

Hope it help