Question

I am building a javascript component for Firefox that will take in a zip code, and will return the current weather conditions.

The sample code that weather underground uses jQuery, but as I understand it, I cannot include this code in my javascript component, as javascript does not have the functionality to include other javascript files.

At any rate, I have built up my skeleton code. It takes in the zip code and builds up the url

(example: http://api.wunderground.com/api/e17115d7e24a448e/geolookup/conditions/q/22203.json)

I have tried downloading the data from that url, via the following method:

getWeatherByUrl: function(url)
{
    var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
    var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD",Components.interfaces.nsILocalFile);
    file.append("weather-forecaster.dat");
    var urlURI = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(url, null, null);        
    persist.saveURI(urlURI,null,null,null,"",file);
    return url;
}

This should download the file to the user's profile directory. It indeed does create the file there. However, it does not look like it contains the json data from weather underground.

What exactly is going on? How would I download the file? I believe that there is a query going on when that url is passed to weather underground, but that shouldn't matter as the .json page is what gets spit out from them, right?

Is there a way to do this without downloading the file, but by streaming it and parsing it?

Was it helpful?

Solution

You can simply use XMLHttpRequest to download this data:

var request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
                        .createInstance(Components.interfaces.nsIXMLHttpRequest);
request.open("GET", "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json");
request.addEventListener("load", function(event)
{
  var data = JSON.parse(request.responseText);
  alert(data.response.version);
}, false);
request.send(null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top