Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-7
rated 0 times [  0] [ 7]  / answers: 1 / hits: 5975  / 11 Years ago, thu, january 23, 2014, 12:00:00

I've just started to learn how to use APIs, but I'm having a little bit of trouble understanding exactly how to utilize them.



I was able to write the following code thanks to some online documentation, but I have some questions about how to add to it:



var xhr = new XMLHttpRequest();
xhr.open(GET, http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml, false); xhr.send();
console.log(xhr);


Now, when I run this code in my browser and I open the console, I get a dropdown with a whole bunch of stuff under it. First of all, how can I get the code to display JUST the response? I want the console to display just the XML to show when I run my code. Second of all, how do I parse the XML? Is there any way to get a value from an XML element and assign it to a JavaScript variable?



Thanks!


More From » xml

 Answers
4

What you are printing is the XMLHttpRequest object itself, while what you actually want is the response from the request you've made. To get the response, you use



xhr.responseXML;


Which is a object of the type document. (See the MDN docs).



To exhibit the code, you can just



console.log(xhr.responseXML);


But to actually work with the response, you'll probably want to do as Josh suggested, and request from the API a JSON-formatted response (instead of a XML-formatted one).



You will probably want to do that asyncronously, too (see this). The page has a more robust example. Let's adapt it to show London's temperature:



var xhr = new XMLHttpRequest();
xhr.open(GET, http://api.openweathermap.org/data/2.5/weather?q=London&mode=json, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
console.log(Temperature(K): + response.main.temp);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);


Being async means that the xhr.onLoad function will be executed as soon as the response is received. Thus all of your code will be executed sequentially, and only when the response is received the onLoad will be executed.


[#48407] Wednesday, January 22, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;