'Cannot Parse properties from HTTPRequest using Javascript - Homework
I am having an issue parsing properties from the response I get to an API call. I can see the results using a console log, but when I attempt to parse the data and display it, I get "undefined" for all the properties. I know fetch is a different animal, but this is an assignment and we need to do it with GET requests. I also know modern JavaScript etiquette doesn't require backwards compatible event listeners, but our book is from 2016.
The relevant JavaScript:
function getRequestObject() {
try {
httpRequest = new XMLHttpRequest();
} catch (requestError) {
return false;
}
return httpRequest;
}
function getResults(evt) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
var entry = document.getElementsByTagName("input")[0].value;
if (!httpRequest) {
httpRequest = getRequestObject();
}
httpRequest.abort();
httpRequest.open("get", "https://api.bing.microsoft.com/v7.0/search?q=" + encodeURIComponent(entry) + "&count");
httpRequest.setRequestHeader("Ocp-Apim-Subscription-Key", "fb8338ec48d44c2dbc002efd2d065b19");
httpRequest.setRequestHeader("Content-Type", "application/json");
httpRequest.send();
httpRequest.onreadystatechange = displaySuggestions;
}
function displaySuggestions() {
console.log("display request.response -" + httpRequest.response);
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
// var response = JSON.stringify(httpRequest.response);
var searchResults = JSON.parse(httpRequest.response);
console.log("after - search results =" + searchResults);
console.log(searchResults);
var articleEl = document.getElementsByTagName("article")[0];
console.log("name" + searchResults.name);
for (var i = 0; i < 20; i++) {
var newDiv = document.createElement("div");
var head = document.createDocumentFragment();
var newP1 = document.createElement("p");
var newP2 = document.createElement("p");
var newP3 = document.createElement("p");
var newA = document.createElement("a");
head.appendChild(newP1);
newA.innerHTML = searchResults.Title;
newA.setAttribute("href", searchResults.Url);
newP1.appendChild(newA);
newP1.className = "head";
newP2.innerHTML = searchResults.Url;
newP2.className = "url";
newP3.innerHTML = searchResults.Description;
newDiv.appendChild(head);
newDiv.appendChild(newP2);
newDiv.appendChild(newP3);
articleEl.appendChild(newDiv);
}
}
}
It is also live on a web server, so here is the url. I am aware of the reference error, it's just a variable that was defined using 'getElementByID' and the element is not on this particular page.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
