首页 > 解决方案 > 当没有显示有效输入时,有没有办法显示消息?

问题描述

这一切仍然很新,但我想知道如果没有显示有效输入(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 (){            
        }

});

});

""""""""""""""""""""""""""""""""""""""""""""""""""" """""""""""""""""""""""""""""""""""""""""""""

标签: javascriptapierror-handling

解决方案


使用 $.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>


推荐阅读