从XMLHTTPRequest获取JSON数据

时间:2017-12-15 02:25:30

标签: javascript json ajax

我需要一些的帮助。

我有一个狗品种列表,在这里:

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

然后就是这个杂物,在这里:

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

我试图从其onload函数中提取terrier子品种数据/对象,并将其APPEND到品种列表中的对象。每次我这样做,我得到的就是XMLHttpRequest对象,而不是对象本身。

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

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

2 个答案:

答案 0 :(得分:0)

尝试在terrierSubBreed之外声明变量terrierSubBreed.onload = function() {},以便您可以使用terrierSubBreedList.message填充它。

尝试这是否有效:

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

答案 1 :(得分:0)

您应该使用辅助函数来发出XMLHttpRequest次请求。

这样的事情:

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

上述帮助函数适用于所有浏览器。

  

<强>其中:

     
      
  • type =可能是HTTP动词,在本例中为GET
  •   
  • url =要请求的网址字符串。
  •   
  • data =可能是null
  •   
  • callback =响应准备就绪时的回调函数。 (this.status === 200 && this.readyState === 4)
  •   

用法:

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

关于你的问题:你应该使用它:

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

对于进入terrier数组的每个子品种,将当前值附加到breeds.message.terrier数组。

这样的事情:

&#13;
&#13;
(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);
    });
  });
}());
&#13;
.as-console-wrapper {
  position: relative;
  top: 0;
}
&#13;
&#13;
&#13;

结果应为:

{
  "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"]
}