点击事件仅在第二次点击后显示数据



我正在研究jQuery.ajax((方法,将一段JSON数据存储在var d中。我在控制台中注意到,在最初单击按钮后,var会被存储,但直到第二次单击才会显示。有人能详细说明这一点并提出解决方案吗?

var d;
$(document).ready(function () {
$('#Weather').click(function () {
var requestData = $('#City').val() + ',' + $('#Country').val();
var unit = 'imperial';
var key = '..........................';
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather',
method: 'get',
data: { q: requestData, units: unit, APPID: key },
dataType: 'json',
success: function (data) {
d = data.main.temp;
}
});
if (d >= 40) {
document.getElementById("Text").value = "Value = " + d + " °";
}
else if (d < 40) {
document.getElementById("Text1").value = "Value = " + d + " °";
}
});
});
<table>
<tr>
<td>Enter City</td>
<td><input type="text" id="City" /></td>
</tr>
<tr>
<td>Enter Country</td>
<td><input type="text" id="Country" /></td>
</tr>
</table>
<button id="Weather" >Get d</button>
<input type="text" id="Text" value="T °" />
<input type="text" id="Text1" value="T °" />

这是JSON

"main": {
"temp": 37.38,
"pressure": 1030,
"humidity": 36,
"temp_min": 35.06,
"temp_max": 39.2
},

谢谢。

如果if/else在AJAX调用之外,则在发送调用后立即执行,即d未定义,然后两个条件都失败。

因此,如果/else已更新d的值,则在success回调内部移动

$('#Weather').click(function () {
var requestData = $('#City').val() + ',' + $('#Country').val();
var unit = 'imperial';
var key = '..........................';
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather',
method: 'get',
data: { q: requestData, units: unit, APPID: key },
dataType: 'json',
success: function (data) {
d = data.main.temp;
if (d >= 40) {
document.getElementById("Text").value = "Value = " + d + " °";
}
else if (d < 40) {
document.getElementById("Text1").value = "Value = " + d + " °";
}
}
});
});

最新更新