在 jQuery 中创建错误处理

Creating error handling in jQuery

本文关键字:错误 处理 创建 jQuery      更新时间:2023-09-26

我正在尝试从jquery为我的文档创建错误消息。

我已经用 JSON 数据填充了一个<select>菜单,它们链接到外部 HTML 文件以显示其位置的天气,我需要的是如果没有该选项的 HTML 文件,则显示错误消息。

例如,地点

是伦敦,纽约,巴黎和罗马,除了罗马之外,所有地点都有一个HTML文件,其中包含天气数据并显示正常,但是当选择罗马时...什么也没发生!在选择另一个位置后选择罗马时,它将保留在当前数据上!

我正在使用jQuery来提取数据等,我的直觉是它需要一个if()语句,但我不确定该语句的条件!

我的jQuery代码在这里...

$(document).ready(function () {
    // The below function pulls in the data from the external JSON file
    $.getJSON('json/destinations.json', function (data) {
        // attaches it to a variable
        var destinations = data.Destinations;
        $(destinations).each(function (id, destination) {
            $('#destinations').append('<option value="' + destination.destinationID + '">' + destination.destinationName + '</option>');
        });
        $("#destinations").change(function () {
            $('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function () {
                $('#weatherForecasts').show("slow");
            });
        });
    });
    // Hide statements for our extra fields and also the weather forecast DIV
    $('#weatherForecasts').hide();
    $('#extraFields').hide();
    $('.errorMessage').hide();
    // Function that allows us to see the extraFields when a radio button is checked!
    $("input[name='survey1']").change(function () {
        $("#extraFields").show("slow");
    });
    $("input[name='survey1']:checked").change(); //trigger correct state onload
});

http://api.jquery.com/load/

在页面底部有一个处理错误的示例:

$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
  if ( status == "error" ) {
    var msg = "Sorry but there was an error: ";
    $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
  }
});

所以在你的情况下

 $("#destinations").change(function () {
     $('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function (response, status, xhr) {
          if (status == 'error'){
             // do error things
          }else{
             $('#weatherForecasts').show("slow");
          }
     });
 });