未定义的响应来自侧边栏小工具中 XHR 的文本

Undefined responseText from XHR in sidebar gadget

本文关键字:工具 文本 XHR 侧边栏 响应 未定义      更新时间:2023-09-26

我正在尝试编写一个小工具,显示 api.openweathermap.org 的当前温度。该小工具通过 setTimeout "循环"中的异步 XMLHttpRequest 提取信息(因此天气数据每隔几分钟更新一次(,但有时 XHR 的响应文本是未定义的,这当然会引发错误并停止循环,并不可避免地停止更新过程。

Fiddler 显示流量熄灭,响应返回有效且预期的数据,但 XHR 无法以某种方式访问它。

相关的 JS 位:

var timer;      // these three 
var locStr;     // are defined 
var weather;    // elsewhere
function showWeather()
{
    System.Debug.outputString('showWeather()');
    if (timer) clearTimeout(timer);
    locStr = System.Gadget.Settings.readString("location");
    // this is for first-run use only - when the setting is not set, display an appropriate notification to the user
    if (locStr == "")
    {
        cell.style.display = 'none';
        welcome.style.display = 'block';
    }
    else
    {
        cell.style.display = 'block';
        welcome.style.display = 'none';
        updateWeather();
    }
}
function updateWeather()
{
    System.Debug.outputString('updateWeather()');
    try
    {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function()
        {
            System.Debug.outputString('updateWeather()>onreadystatechange ' + xhr.status + ' ' + xhr.readyState);
            if (xhr.status === 200)
            {
                if (xhr.readyState === 4)
                {
                    // this is what makes it fail:
                    System.Debug.outputString(xhr.responseText);
                    weather = eval('(' + xhr.responseText + ')'); // i DO get that eval is evil, but works for my purposes well.
                    // temp, city, wind and clouds are html entities id values
                    temp.innerHTML = Math.round(weather.main.temp) + '<span>&deg;C</span>';
                    city.innerHTML = weather.name;
                    wind.innerHTML = weather.wind.speed + ' m/s';
                    clouds.innerHTML = weather.clouds.all + '%';
                    // clears and hides error, if occured in previous fetch
                    error_title.innerHTML = '';
                    error_description.innerHTML = '';
                    error.style.display = 'none';
                    timer = setTimeout(updateWeather, 1000 * 5);
                }
                else
                {
                    temp.innerText += '.';
                }
            }
            else
            {
                error_title.innerText = 'Connectivity error';
                error_description.innerText = xhr.status + '.'; // that's really informative...
                error.style.display = 'block';
                timer = setTimeout(updateWeather, 5000)
            }
        };
        xhr.ontimeout = function()
        {
            error_title.innerText = 'Connectivity error';
            error_description.innerText = 'timed out';
            error.style.display = 'block';
            timer = setTimeout(updateWeather, 5000);
        };
        xhr.open('get', 'http://api.openweathermap.org/data/2.5/weather?q=' + locStr + '&units=metric&dummy=' + Math.ceil(100*Math.random()), false);
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.send();
    }
    catch (e)
    {
        error_title.innerText = e.name;
        error_description.innerText = e.message;
        error.style.display = 'block';
        timer = setTimeout(updateWeather, 5000);
    }
}

showWeather()在窗口的 onload 事件中调用,然后检查用户是否在首选项中设置了位置(城市(,并在 updateWeather(( 中启动循环。

然后,updateWeather()发出请求并适当地处理数据,这有效,但只要我不尝试访问 responseText。

我对

这个问题很不知所措,但我觉得我在这里错过了一些基本的东西,而且我对 JS 还不是很有经验。

我想在这里使用纯javascript,对我来说没有花哨的库。

请指教。

更新

我做了一些更改和测试,这是我发现的:

  1. 我使用了不同的网络服务 - 雅虎天气和小工具完美运行。Yahoo返回XML,OpenWeatherApi - JSON。我还不知道这是否与我的问题有关,因为正如我之前所说 - OWA 有时会起作用。

  2. CORS绝对不是小工具的问题。这个小提琴无法检索数据,在检查器中我可以看到一条消息,指出

    XMLHttpRequest cannot load http://weather.yahooapis.com/forecastrss?w=526363&u=c.
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    Origin 'http://fiddle.jshell.net' is therefore not allowed access.
    

    然而,在我的小工具中,检索数据没有问题。

这很可能是由于浏览器中实现的跨域安全策略(跨域资源共享 – CORS、W3C(机制。通过javascript对来自不同域的资源的HTTP请求将失败(如果服务器支持,您可以使用JSONP解决此问题(。要启用 CORS,您尝试连接的服务器需要将您的域添加到"访问控制允许来源"HTTP 标头或允许所有域(使用星号通配符"*"表示(。

MDN 文章供参考 - https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS

有人已经记录了这个问题:http://bugs.openweathermap.org/issues/152