OpenWeatherMap APIを呼び出して、天気予報の JSON オブジェクトを取得しています。誰かが zipweather html id 要素に郵便番号を入力して送信または入力を押したときに呼び出される 3 つの異なる JavaScript メソッドを使用し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;
}
最後の 2 つの方法は、jQuery を使用して失敗したときに AJAX 要求を再試行する最良の方法は何ですか? で見つけた可変トリックを使用retryCount
します。そのため、ダウンしている場合は API を呼び出し続けません。retryMax
最後に、質問:
これらの方法はすべて、パフォーマンスの点で実質的に同じですか? 書かれている方法に致命的なバグが潜んでいる可能性はありますか?
AJAX を使用する場合、同じ関数に対してエラー ハンドラでコールバックを使用するのが最も適切ですか?
onreadystatechange
JavaScript コード標準は、イベント ハンドラの使用から、jquery$.ajax
および$.get
関数へと移行していますか?
みんな、ありがとう。長くなってすみません!