我正在调用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。
最后,问题:
所有这些方法在性能方面是否几乎相同?在所写的任何方法中是否存在潜在的灾难性错误?
使用 AJAX 时,在错误处理程序中对同一函数使用回调是否最合适?
javascript 代码标准是否正在从使用
onreadystatechange
或事件处理程序转向 jquery$.ajax
和$.get
函数?
感谢大家。抱歉,拖了这么久!