简体   繁体   中英

Javascript works in FF / IE but not Chrome / Safari

I'm working on a Drupal 6 module where I use jquery (and more specifically, the $.ajax method) to retrieve a RSS feed from Yahoo's weather API. I decided against using the JFeed library because I need access to the elements with "yweather" prefix (and I couldn't find a way of accessing them via JFeed). I decided to use the $.ajax method and parse the XML response instead. The JavaScript code below works fine in Firefox and IE but does not work in Safari (or Chrome FWIW):

function parseXml(xml) {
  var atmosphere = xml.getElementsByTagName("yweather:atmosphere");

  var humidity = atmosphere[0].getAttribute("humidity");

  $('#weatherFeed').html("Humidity: " + humidity);
  $('#weatherFeed').append(
     "<div style=\"text-align: center;margin-left: auto; margin-right: auto;\">" + 
     city + ", " + state + "</div>");
}

function getData(){
   $.ajax({
      type:   'GET',
      url:    'proxy.php?url=http://weather.yahooapis.com/forecastrss&p=94041',
      dataType: 'xml',
      success:  function(xml) {
      parseXml(xml);
 }
 }); 
}

if(Drupal.jsEnabled) {
$(function() {
      getData();
      setInterval("getData()", 30000);
      });   
}

When I check the error console in Safari I see the following error message: TypeError: Result of expression 'atmosphere[0]' [undefined] is not an object. Is there an issue with using getElementsByTagName in Safari? Should I be accessing the object that's returned by getElementsByTagName differently?

Maybe just treating the the XML as data and using jQuery selectors to pull out what you want would work.

$(xml).find("yweather:atmosphere").attr("humidity") - you might need to use filter instead of find - what do you think?

I had the exact same problem, but came across the answer here: http://reference.sitepoint.com/javascript/Document/getElementsByTagName

It has to do with the yweather namespace. Use getElementByTagNameNS function instead.

var atmosphere = xml.getElementsByTagName("yweather:atmosphere");

becomes

var atmosphere = xml.getElementsByTagNameNS("http://xml.weather.yahoo.com/ns/rss/1.0","atmosphere");

function reference: http://reference.sitepoint.com/javascript/Document/getElementsByTagNameNS

在Chrome和Safari浏览器中,您是否尝试过用气压[1]而不是0?

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