0

我正在调用OpenWeatherMap API以获取天气预报 JSON 对象。我使用了 3 种不同的 javascript 方法,当有人在 zipweather html id 元素中输入邮政编码并按下提交或输入时调用这些方法,调用zipWeather()并基本上将邮政编码粘贴到 api 地址的末尾,然后发送回该邮政编码上的数据。

他们都工作正常。他们都有一个城市名称和温度,转换为华氏温度。

它们都在错误处理程序中对函数本身使用回调,以防失败。第一个使用 5 秒超时回调。

onreadystatechange方法:

function zipWeather() {
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
//responseText code
}
// else ifs for readystate 3 2 and 1 gives a console log
else {
console.log("request failed, retrying in 5 seconds...");
window.setTimeout(zipWeather, 5000);
return;
}
}
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + document.getElementById("zipweather").value,
true);

xhr.send();

事件侦听器而不是onreadystatechange

xhr.addEventListener("load", function() {
//responseText code
}, false)

xhr.addEventListener("error", function(err) {
console.log(err);
if (weatherData.retryCount <= weatherData.retryMax) {
    weatherData.retryCount++;
    console.log(weatherData.retryCount);
    console.log(err);
    zipWeather();
    return;
    }
else {
return;
}

当然还有jquery:

function zipWeather() {
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + $("#zipweather").val(),
data: {},
dataType: 'json',
success: function(data) {
console.log(data.name);
$('#weather').html(data.name).css({'color': 'blue', 'text-shadow': '1px 0.5px lightblue'});
//change from kelvin
var localTempF = Math.round((data.main.temp - 273.15) * 9/5 + 32);
$('#localtemp').html(localTempF + weatherData.localUnits);
weatherData.localTemperatureValue = localTempF;
},
timeout: 3000,
retryCount: 0,
retryMax: 5,
error: function(jqXHR, textStatus, errorThrown) { 
this.retryCount++;
    if (this.retryCount <= this.retryMax) {
    //try again
    $.ajax(this);
    return;
    }
return;
}

retryCount最后两种方法使用retryMax我在What's the best way to retry a AJAX request on failure using jQuery? 因此,如果它关闭,它不会继续调用 API。

最后,问题:

  1. 所有这些方法在性能方面是否几乎相同?在所写的任何方法中是否存在潜在的灾难性错误?

  2. 使用 AJAX 时,在错误处理程序中对同一函数使用回调是否最合适?

  3. javascript 代码标准是否正在从使用onreadystatechange或事件处理程序转向 jquery$.ajax$.get函数?

感谢大家。抱歉,拖了这么久!

4

2 回答 2

1

您可能可以使用性能测试工具自己回答性能问题。我更喜欢事件监听器,因为代码读起来更干净。就错误而言,如果服务关闭,我会将第一种方法无法打破回调循环的方法归类为严重错误。如果服务关闭,可能会导致性能下降,这需要通过性能测试来检查。

我不知道是否有在错误处理程序中重新调用该方法的约定,但只要您有循环中断,这似乎是一种处理它的好方法。如果达到最大重试次数,您可能希望提醒用户并提示他们将在一段时间后再次尝试服务调用。有关此行为的示例,请参阅 Gmail 处理连接中断的方式。

至于 jQuery v. not jQuery,这取决于您的用例。在您执行最少的 JavaScript 编码的轻量级网页中,您可能会发现 jQuery 在库的大小方面是多余的。另一方面,jQuery 之所以流行,是因为它解决了浏览器的不兼容问题,让您(编码人员)专注于应用程序功能。如果您从流行的 CDN 加载它,许多用户可能已经在缓存中拥有它,因此加载时间不会是一个因素。至于人们使用什么,jQuery 很流行,但除此之外,我不知道是否有任何统计数据可以打破这两种方法的相对流行度。

于 2015-04-27T19:55:49.017 回答
-1

回答你的三个问题:

1. 性能

由于在 JavaScript 中发送请求的方式根本不会影响实际的网络加载性能,因此根本不重要。此外,三者之间几乎没有客户端性能差异。


2.失败时回调

你处理得非常好和优雅。不要担心一种方法,除非它很慢或不起作用:D


3. 哪一个?

这完全取决于你!如果你想做 jQuery,那就去做吧。如果你想用事件监听器来做纯 JavaScript,那就去做吧。


希望对你有帮助,如果有什么问题,欢迎提问:)

于 2015-04-27T19:22:09.010 回答