所有这一切仍然很新,但是我想知道如果没有显示有效输入(404消息),是否有办法显示错误消息。
如果未在输入框中输入任何内容,则错误消息有效,但是如果用户未正确拼写例如“ London”,则控制台将显示404消息,而我不知道如何显示错误消息谢谢您。
"""""""""""""""""""""""""""""""""""""""""""""""""""" """"""""""""""""""""""""""""""""""""""""""""""""""
$('#submitweather').click(function(){
var city = $("#city").val();//declares variable name "city"
if(city !== ''){ //if the input box is not empty
$.ajax({
//first part, web address. second part, global variable. third part, UK uses metric. fourth part, API key.
url: 'http://api.openweathermap.org/data/2.5/weather?q='+city+"&units=metric"+"&APPID=???",
type: "GET",
datatype: "JSONP", //JSON with padding
success: function(data){
//console.log(data); test worked
var widget = show (data);
$("#show").html(widget);
$("#city").val('');} // empties input box when finished
});
}
else if(city == ''){
$("#error").html('Cannot Be Empty').fadeOut(10000);
}
else (){
}
});
});
"""""""""""""""""""""""""""""""""""""""""""""""""""" """"""""""""""""""""""""""""""""""""""""""""""""""
答案 0 :(得分:1)
使用$ .ajax错误处理程序来捕获未找到或未经授权的错误,例如:
$('#submitweather').click(function(){
var city = $("#city").val(); //declares variable name "city"
if(city !== ''){ //if the input box is not empty
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q='+city+"&units=metric"+"&APPID=???",
type: "GET",
datatype: "JSONP", //JSON with padding
success: function(data){
// You could check the API response as well
if (data.cod == 200){ // API specifies "cod" for the response code.
$("#show").html(data);
$("#city").val('');
}else{
$("#error").html(data.cod+" "+data.message).fadeOut(10000);
}
},
error: function(jqXHR, textStatus, errorThrown){
$("#error").html(textStatus+" "+errorThrown).fadeOut(10000);
}
});
}
else if(city == ''){
$("#error").html('Cannot Be Empty').fadeOut(10000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="city" value="Londron" />
<button id="submitweather">Check weather</button>
</div>
<h2>Result</h2>
<div id="show"></div>
<h2>Error</h2>
<div id="error"></div>