javascript - 当没有显示有效输入时,有没有办法显示消息?
问题描述
这一切仍然很新,但我想知道如果没有显示有效输入(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 (){
}
});
});
""""""""""""""""""""""""""""""""""""""""""""""""""" """""""""""""""""""""""""""""""""""""""""""""
解决方案
使用 $.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>
推荐阅读
- python - 如何将多个 QPushButtons 连接到一个方法?
- java - 评估项目 ':buildSrc' 时出现问题。> 提供的字符串模块符号“gradleApi()”无效
- python - 如何仅在代码第一次运行时在 python 中运行函数?
- javascript - Microsoft Excel 加载项中的“附加调试器”选项不可用
- swift - 结合管道从压缩发布者下载图像
- r - 具有 90 种效果大小的森林图(metafor):如何使文本可读并调整行间距
- td-engine - TDengine 在 Time-dimension Aggregation 查询中的 fill(LINEAR) 不起作用
- string - 如何将包含单引号的输出放入 Powershell 中的字符串中?
- java - Java中可重入锁中的“重入”到底是什么?
- flutter - 配置项目 image_cropper 时出现问题