简体   繁体   中英

Getting JSON data from XMLHttpRequest

I need a little help with some .

I have a list of dog breeds, here:

breedListRequest.onload = function () {
   var breedListData = JSON.parse(this.response);
   var breeds = breedListData.message;
   console.log('All Breeds');
   console.log(breeds);
   console.log('Test');
   console.log(terrierSubBreed); // Testing sub breed object in console.
}

Then there's this subbreed, here:

terrierSubBreed.onload = function() {
  var terrierSubBreedList = JSON.parse(this.response);
  var terrierSubBreed = terrierSubBreedList.message;
  console.log('Terrier Subbreed');
  console.log(terrierSubBreed);
  return terrierSubBreed;
}

I am attempting to pull the terrier sub breed data / object from its onload function, and APPEND it to the object in the Breed List. Every time I do, alls I get is the XMLHttpRequest object, and not the object itself.

https://dog.ceo/api/breeds/list/all

https://dog.ceo/api/breed/terrier/list

You should use a helper function to makeXMLHttpRequest requests without problems.

Something like this:

var newXHR = null;   
function sendXHR(type, url, data, callback) {
  newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(type, url, true);
  newXHR.send(data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response);
    }
  };
}

The above helper function works in all browsers.

Where:

  • type = Could be a HTTP verb, in this case GET .
  • url = URL string to request.
  • data = Could be null .
  • callback = Callback function when the response is ready. (this.status === 200 && this.readyState === 4) .

Usage:

// First request.
sendXHR("GET", "https://dog.ceo/api/breeds/list/all", null, function(response) {
  breeds = JSON.parse(response); // Stores the data of dog breeds in breeds variable.

  // Second request.
  sendXHR("GET", "https://dog.ceo/api/breed/terrier/list", null, function(response) {
    subBreeds = JSON.parse(response); // Stores the data of dog sub breed in subBreeds variable.

    subBreeds.message.map(function(x) { // For every sub breed appends the current value to the breeds.message.terrier array.
      breeds.message.terrier.push(x); // x = sub breed.
    });
    console.log(breeds.message);
  });
});

About your question: You should use this:

subBreeds.message.map(function(x) {
  breeds.message.terrier.push(x);
});

For every sub breed into the terrier array, appends the current value to the breeds.message.terrier array.

Something like this:

 (function() { var newXHR = null, // Defined in the global scope. So we can abort XHR requests when it's necessary. breeds = {}, // Declare the breeds object in the global scope. subBreeds = {}; // Declare the subBreeds object in the global scope. function sendXHR(type, url, data, callback) { newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP"); newXHR.open(type, url, true); newXHR.send(data); newXHR.onreadystatechange = function() { // Use onreadystatechange instead onload. if (this.status === 200 && this.readyState === 4) { callback(this.response); } }; } sendXHR("GET", "https://dog.ceo/api/breeds/list/all", null, function(response) { breeds = JSON.parse(response); sendXHR("GET", "https://dog.ceo/api/breed/terrier/list", null, function(response) { subBreeds = JSON.parse(response); subBreeds.message.map(function(x) { breeds.message.terrier.push(x); }); console.log(breeds.message); }); }); }());
 .as-console-wrapper { position: relative; top: 0; }

The result should be:

{
  "affenpinscher": [],
  "african": [],
  "airedale": [],
  "akita": [],
  "appenzeller": [],
  "basenji": [],
  "beagle": [],
  "bluetick": [],
  "borzoi": [],
  "bouvier": [],
  "boxer": [],
  "brabancon": [],
  "briard": [],
  "bulldog": ["boston", "french"],
  "bullterrier": ["staffordshire"],
  "cairn": [],
  "chihuahua": [],
  "chow": [],
  "clumber": [],
  "collie": ["border"],
  "coonhound": [],
  "corgi": ["cardigan"],
  "dachshund": [],
  "dane": ["great"],
  "deerhound": ["scottish"],
  "dhole": [],
  "dingo": [],
  "doberman": [],
  "elkhound": ["norwegian"],
  "entlebucher": [],
  "eskimo": [],
  "germanshepherd": [],
  "greyhound": ["italian"],
  "groenendael": [],
  "hound": ["Ibizan", "afghan", "basset", "blood", "english", "walker"],
  "husky": [],
  "keeshond": [],
  "kelpie": [],
  "komondor": [],
  "kuvasz": [],
  "labrador": [],
  "leonberg": [],
  "lhasa": [],
  "malamute": [],
  "malinois": [],
  "maltese": [],
  "mastiff": ["bull", "tibetan"],
  "mexicanhairless": [],
  "mountain": ["bernese", "swiss"],
  "newfoundland": [],
  "otterhound": [],
  "papillon": [],
  "pekinese": [],
  "pembroke": [],
  "pinscher": ["miniature"],
  "pointer": ["german"],
  "pomeranian": [],
  "poodle": ["miniature", "standard", "toy"],
  "pug": [],
  "pyrenees": [],
  "redbone": [],
  "retriever": ["chesapeake", "curly", "flatcoated", "golden"],
  "ridgeback": ["rhodesian"],
  "rottweiler": [],
  "saluki": [],
  "samoyed": [],
  "schipperke": [],
  "schnauzer": ["giant", "miniature"],
  "setter": ["english", "gordon", "irish"],
  "sheepdog": ["english", "shetland"],
  "shiba": [],
  "shihtzu": [],
  "spaniel": ["blenheim", "brittany", "cocker", "irish", "japanese", "sussex", "welsh"],
  "springer": ["english"],
  "stbernard": [],
  "terrier": ["american", "australian", "bedlington", "border", "dandie", "fox", "irish", "kerryblue", "lakeland", "norfolk", "norwich", "patterdale", "scottish", "sealyham", "silky", "tibetan", "toy", "westhighland", "wheaten", "yorkshire", "american", "australian", "bedlington", "border", "dandie", "fox", "irish", "kerryblue", "lakeland", "norfolk", "norwich", "patterdale", "scottish", "sealyham", "silky", "tibetan", "toy", "westhighland", "wheaten", "yorkshire"],
  "vizsla": [],
  "weimaraner": [],
  "whippet": [],
  "wolfhound": ["irish"]
}

Try declaring the variable terrierSubBreed outside of the terrierSubBreed.onload = function() {} so that you can fill it with the terrierSubBreedList.message .

Try if this works:

// Somewhere above, outside of functions
var terrierSubBreed = '';

terrierSubBreed.onload = function() 
{
    var terrierSubBreedList = JSON.parse(this.response);
    terrierSubBreed = terrierSubBreedList.message;
    console.log('Terrier Subbreed');
    console.log(terrierSubBreed);
}

breedListRequest.onload = function () 
{
    // ...

    if(terrierSubBreed.length > 0) console.log(terrierSubBreed);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM