0

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

最後に、質問:

  1. これらの方法はすべて、パフォーマンスの点で実質的に同じですか? 書かれている方法に致命的なバグが潜んでいる可能性はありますか?

  2. AJAX を使用する場合、同じ関数に対してエラー ハンドラでコールバックを使用するのが最も適切ですか?

  3. onreadystatechangeJavaScript コード標準は、イベント ハンドラの使用から、jquery$.ajaxおよび$.get関数へと移行していますか?

みんな、ありがとう。長くなってすみません!

4

2 に答える 2

-1

3 つの質問への回答:

1.パフォーマンス

JavaScript でリクエストを送信する方法は、実際のネットワーク負荷のパフォーマンスにはまったく影響しないため、まったく問題になりません。また、3 つの間にクライアント側のパフォーマンスの違いはほとんどありません。


2. 失敗時のコールバック

あなたはそれを実際に非常にうまくエレガントに処理します。メソッドが遅いか機能しない場合を除き、メソッドについて心配する必要はありません:D


3.どれ?

それはあなた次第です!jQuery を実行したい場合は実行してください。イベント リスナーを使用してプレーンな JavaScript を実行したい場合は、それを実行してください。


ご不明な点がございましたら、お気軽にお問い合わせください:)

于 2015-04-27T19:22:09.010 に答える