【问题标题】:Is there a way to display a message when no valid input is displayed?当没有显示有效输入时,有没有办法显示消息?
【发布时间】:2020-03-31 14:12:53
【问题描述】:

这一切仍然很新,但我想知道如果没有显示有效输入(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 调用中添加一个错误处理程序。

标签: javascript api error-handling


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2021-07-13
    • 1970-01-01
    • 2014-08-14
    • 2021-02-15
    • 2019-11-28
    相关资源
    最近更新 更多