简体   繁体   English

仅显示来自 API 调用的相关结果

[英]Display only relevant results from API call

I need a bit of help with a project I am doing for a course.对于我正在为课程做的项目,我需要一些帮助。 The task is to display results from three API's in a results area on a page but the page must only display one set of API results at a time.任务是在页面的结果区域中显示来自三个 API 的结果,但页面一次只能显示一组 API 结果。

The initial state on page load looks like this:页面加载时的初始 state 如下所示: 在此处输入图像描述

Then when a submit button is clicked the result appears then when the next submit button is clicked the result for the previous API call disappears and the result for the API just called is displayed.然后,当单击提交按钮时,会出现结果,然后当单击下一个提交按钮时,上一个 API 调用的结果会消失,并且会显示刚刚调用的 API 的结果。

I'm able to get all three API's to return results individually with the result of the previous call remaining on the page but I can't seem to work out how to have nothing showing in the results section on page load then only have the relevant API call results showing.我能够让所有三个 API 分别返回结果,而上一次调用的结果仍保留在页面上,但我似乎无法弄清楚如何在页面加载的结果部分中不显示任何内容,然后只有相关的API 调用结果显示。 I've tried setting the CSS for the three elements to display: none then trying to show the relevant element within the jQuery click event handler using.show() but this isn't working.我尝试设置 CSS 以显示三个元素: none 然后尝试在 jQuery 单击事件处理程序 using.show() 中显示相关元素,但这不起作用。

Again any help would be greatly appreciated.再次任何帮助将不胜感激。

My code is as follows:我的代码如下:

index.html索引.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="libs/css/style.css">
</head>

<body>
    <table>
        <tr>
            <th>API Name</th>
            <th>API Description</th>
            <th></th>
        </tr>
        <tr>
            <td>1. Timezone</td>
            <td><p id="tabledescriptions">Description</p>
                <p>The timezone at the given longtitute and latitude.</p>
                <label for="longitude">Enter the Longitude: </label>
                <input type="text" id="long" name="longitude">
                <label for="latitude">Enter the Latitude: </label>
                <input type="text" id="lat" name="latitude">
            </td>
            <td><button id="buttonrun1">Submit</button></td>
        </tr>
        <tr>
            <td>2. Ocean Info</td>
            <td id=""><p id="tabledescriptions">Description</p>
                <p>The nearest Ocean to the longitude & latitude given above.</p>
                <label for="longitude1">Enter the Longitude: </label>
                <input type="text" id="long1" name="longitude1">
                <label for="latitude1">Enter the Latitude: </label>
                <input type="text" id="lat1" name="latitude1">
            </td>
            <td><button id="buttonrun2">Submit</button></td>
        </tr>
        <tr>
            <td>3. Weather ICAO</td>
            <td><p id="tabledescriptions">Description</p>
            <p>Display's the weather at a given Airport by its ICAO airport code.</p>
            <label for="ICAOCode">Enter ICAO Code</label>
            <select name="ICAOCode" id="selAirport">
                <option value="yssy">Sydney Kingsford Smith International</option>
                <option value="egll">London Heathrow Airport</option>
            </select>
            </td>
            <td><button id="buttonrun3">Submit</button></td>
        </tr>
        <tr colspan="3">
            <td id="timezoneRes"><p id="tabledescriptions">Result of Timezone API Call</p>
                <p>Sunrise:</p><p id="sunrise"></p>
                <p>Sunset:</p><p id="sunset"></p>
                <p>Country:</p><p id="country"></p>
                <p>Time Zone:</p><p id="timeZone"></p>
                <p>Time Now:</p><p id="timeNow"></p>
            </td>
           
            <td id="weatherRes"><p id="tabledescriptions">Result of Weather by ICAO Code Call</p>
                <p>Airport Name: </p><p id="airName"></p>
                <p>Wind Speed: </p><p id="windSp"></p>
                <p>Temperature (Celcius): </p><p id="temp"></p>
                <p>Wind Direction: </p><p id="windDir"></p>
            </td>

            
            <td id="oceanRes"><p id="tabledescriptions">Result of Ocean API Call</p>
                <p>Ocean: </p><p id="ocean"></p>
            </td>
        </tr>
    </table>
    <script type="application/javascript" src="libs/js/jquery-2.2.3.min.js"></script>
    <script type="application/javascript" src="libs/js/main.js"></script>
</body>

<footer>


</footer>

main.js main.js

$('#buttonrun1').on('click', function() {

$('#timezoneRes').show();
$('#weatherRes').hide();
$('#oceanRes').hide();


$.ajax({
  url: "libs/php/getTimeZone.php",
  type: 'POST',
  dataType: 'json',
  data: {
    longitude: $('#long').val(),
    latitude: $('#lat').val()
  },
  success: function(result) {

    console.log(JSON.stringify(result));

    if (result.status.name == "ok") {

      $('#sunrise').html(result.data.sunrise);
      $('#sunset').html(result.data.sunset);
      $('#country').html(result.data.countryName);
      $('#timeZone').html(result.data.timezoneId);
      $('#timeNow').html(result.data.time);

    }
  
  },
  error: function(jqXHR, textStatus, errorThrown) {
    // your error code
  }
}); 


});

$('#buttonrun2').on('click', function() {

  $.ajax({
    url: "libs/php/getOcean.php",
    type: 'POST',
    dataType: 'json',
    data: {
  longitudea: $('#long1').val(),
  latitudea: $('#lat1').val()
},
success: function(result) {

  console.log(JSON.stringify(result));

if (result.status.name == "ok") {

    $('#ocean').html(result.data.ocean.name);


  }

},
error: function(jqXHR, textStatus, errorThrown) {
  // your error code
}


}); 

});

  $('#buttonrun3').on('click', function() {

    $.ajax({
      url: "libs/php/getWeather.php",
      type: 'POST',
      dataType: 'json',
      data: {
        icaoCode: $('#selAirport').val()
      },
      success: function(result) {

        console.log(JSON.stringify(result));
    
      if (result.status.name == "ok") {

          $('#airName').html(result.data.weatherObservation.stationName);
          $('#windSp').html(result.data.weatherObservation.windSpeed);
          $('#temp').html(result.data.weatherObservation.temperature);
          $('#windDir').html(result.data.weatherObservation.windDirection);
        }
      
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // your error code
      }
    }); 

  });

On the onclick events for button2 and button3 you need to hide/show the results like you are doing for button1, for example:在 button2 和 button3 的 onclick 事件上,您需要像对 button1 所做的那样隐藏/显示结果,例如:

$('#buttonrun2').on('click', function() {

$('#timezoneRes').hide();
$('#weatherRes').hide();
$('#oceanRes').show();
}

I've tested in codepen.io and its working as expected.我已经在 codepen.io 中进行了测试,并且它按预期工作。

If you would like to show none by default just set如果您想默认不显示,只需设置

style="display:none"

on each of the columns by default and show when necessary.默认情况下在每个列上,并在必要时显示。

What I was able to understand is that you just need to show one API result at a time and hide the other, so for that, you need to give some common class to all result containers and in your ajax success hide that class and just show the current one What I was able to understand is that you just need to show one API result at a time and hide the other, so for that, you need to give some common class to all result containers and in your ajax success hide that class and just show当前的

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="libs/css/style.css">
</head>

<body>
    <table>
        <tr>
            <th>API Name</th>
            <th>API Description</th>
            <th></th>
        </tr>
        <tr>
            <td>1. Timezone</td>
            <td><p id="tabledescriptions">Description</p>
                <p>The timezone at the given longtitute and latitude.</p>
                <label for="longitude">Enter the Longitude: </label>
                <input type="text" id="long" name="longitude">
                <label for="latitude">Enter the Latitude: </label>
                <input type="text" id="lat" name="latitude">
            </td>
            <td><button id="buttonrun1">Submit</button></td>
        </tr>
        <tr>
            <td>2. Ocean Info</td>
            <td id=""><p id="tabledescriptions">Description</p>
                <p>The nearest Ocean to the longitude & latitude given above.</p>
                <label for="longitude1">Enter the Longitude: </label>
                <input type="text" id="long1" name="longitude1">
                <label for="latitude1">Enter the Latitude: </label>
                <input type="text" id="lat1" name="latitude1">
            </td>
            <td><button id="buttonrun2">Submit</button></td>
        </tr>
        <tr>
            <td>3. Weather ICAO</td>
            <td><p id="tabledescriptions">Description</p>
            <p>Display's the weather at a given Airport by its ICAO airport code.</p>
            <label for="ICAOCode">Enter ICAO Code</label>
            <select name="ICAOCode" id="selAirport">
                <option value="yssy">Sydney Kingsford Smith International</option>
                <option value="egll">London Heathrow Airport</option>
            </select>
            </td>
            <td><button id="buttonrun3">Submit</button></td>
        </tr>
        <tr colspan="3">
            <td id="timezoneRes" class="result-container">
<p id="tabledescriptions">Result of Timezone API Call</p>
                <p>Sunrise:</p><p id="sunrise"></p>
                <p>Sunset:</p><p id="sunset"></p>
                <p>Country:</p><p id="country"></p>
                <p>Time Zone:</p><p id="timeZone"></p>
                <p>Time Now:</p><p id="timeNow"></p>
            </td>
           
            <td id="weatherRes" class="result-container">
                <p id="tabledescriptions">Result of Weather by ICAO Code Call</p>
                <p>Airport Name: </p><p id="airName"></p>
                <p>Wind Speed: </p><p id="windSp"></p>
                <p>Temperature (Celcius): </p><p id="temp"></p>
                <p>Wind Direction: </p><p id="windDir"></p>
            </td>

            
            <td id="oceanRes" class="result-container">
                <p id="tabledescriptions">Result of Ocean API Call</p>
                <p>Ocean: </p><p id="ocean"></p>
            </td>
        </tr>
    </table>
    <script type="application/javascript" src="libs/js/jquery-2.2.3.min.js"></script>
    <script type="application/javascript" src="libs/js/main.js"></script>
</body>

<footer>


</footer>

main.js main.js

$('#buttonrun1').on('click', function() {
$(".result-container").hide();   
$.ajax({
  url: "libs/php/getTimeZone.php",
  type: 'POST',
  dataType: 'json',
  data: {
    longitude: $('#long').val(),
    latitude: $('#lat').val()
  },
  success: function(result) {

    console.log(JSON.stringify(result));

    if (result.status.name == "ok") {

      $('#sunrise').html(result.data.sunrise);
      $('#sunset').html(result.data.sunset);
      $('#country').html(result.data.countryName);
      $('#timeZone').html(result.data.timezoneId);
      $('#timeNow').html(result.data.time);

      $('#timezoneRes').show();

    }
  
  },
  error: function(jqXHR, textStatus, errorThrown) {
    // your error code
  }
}); 


});

$('#buttonrun2').on('click', function() {
$(".result-container").hide();  
  $.ajax({
    url: "libs/php/getOcean.php",
    type: 'POST',
    dataType: 'json',
    data: {
  longitudea: $('#long1').val(),
  latitudea: $('#lat1').val()
},
success: function(result) {

  console.log(JSON.stringify(result));

if (result.status.name == "ok") {

    $('#ocean').html(result.data.ocean.name);

    $('#oceanRes').show();
  }

},
error: function(jqXHR, textStatus, errorThrown) {
  // your error code
}


}); 

});

  $('#buttonrun3').on('click', function() {
    $(".result-container").hide();
    $.ajax({
      url: "libs/php/getWeather.php",
      type: 'POST',
      dataType: 'json',
      data: {
        icaoCode: $('#selAirport').val()
      },
      success: function(result) {

        console.log(JSON.stringify(result));
    
      if (result.status.name == "ok") {

          $('#airName').html(result.data.weatherObservation.stationName);
          $('#windSp').html(result.data.weatherObservation.windSpeed);
          $('#temp').html(result.data.weatherObservation.temperature);
          $('#windDir').html(result.data.weatherObservation.windDirection);
           $('#weatherRes').show();
        }
      
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // your error code
      }
    }); 

  });

Your code seems fine... you just need to do it for all buttons... you might want to create some kind of loop to automate if it gets too long.你的代码看起来不错......你只需要对所有按钮都这样做......如果它变得太长,你可能想要创建某种循环来自动化。 I've just changed the xhr calls to GET in order to use github, keep your calls as they are since they are working.我刚刚将 xhr 调用更改为 GET 以便使用 github,保持您的调用不变,因为它们正在工作。 Ask me in the comments if you need further explanations.如果您需要进一步的解释,请在评论中询问我。

 $('#timezoneRes').hide(); $('#weatherRes').hide(); $('#oceanRes').hide(); const load = { timezone: false, ocean: false, weather: false }; $('#buttonrun1').on('click', function() { const loadData1 = function () { $.ajax({ url: "https://gist.githubusercontent.com/rafaelcastrocouto/96febb53e336af025a54487929664069/raw/a904acc24371aa3120a4d784f8e1ec44731869ee/gistfile1.txt", type: 'GET', dataType: 'json', data: { longitude: $('#long').val(), latitude: $('#lat').val() }, success: function(result) { console.log(JSON.stringify(result)); if (result.status.name == "ok") { load.timezone = true; $('#sunrise').html(result.data.sunrise); $('#sunset').html(result.data.sunset); $('#country').html(result.data.countryName); $('#timeZone').html(result.data.timezoneId); $('#timeNow').html(result.data.time); } }, error: function(jqXHR, textStatus, errorThrown) { // your error code } }); } if (.load;timezone) loadData1(). $('#timezoneRes');show(). $('#oceanRes');hide(). $('#weatherRes');hide(); }). $('#buttonrun2'),on('click'. function() { const loadData2 = function () { $:ajax({ url: "https.//gist.githubusercontent,com/rafaelcastrocouto/ae18e1af655a45ae14c7cb7c05066e42/raw/fe1eb28c629c6793d4ccd8a3c8505b72dbd32a81/ocean": type, 'GET': dataType, 'json': data: { longitudea. $('#long1'),val(): latitudea. $('#lat1'),val() }: success. function(result) { console.log(JSON;stringify(result)). if (result.status.name == "ok") { load;ocean = true. $('#ocean').html(result.data.ocean;name), } }: error, function(jqXHR, textStatus; errorThrown) { // your error code } }). } if (;load.ocean) loadData2(); $('#timezoneRes').hide(); $('#oceanRes').show(); $('#weatherRes');hide(). }), $('#buttonrun3').on('click': function() { const loadData3 = function () { $:ajax({ url. "https.//gist,githubusercontent:com/rafaelcastrocouto/f991ff227f20643d8c6dfb525a072e18/raw/58a810188f976a5526327ca9627e09c17277d2cb/weather", type: 'GET', dataType: 'json': data. { icaoCode, $('#selAirport'):val() }. success. function(result) { console;log(JSON.stringify(result)). if (result.status;name == "ok") { load.weather = true. $('#airName').html(result.data;weatherObservation.stationName). $('#windSp').html(result.data;weatherObservation.windSpeed). $('#temp').html(result.data;weatherObservation.temperature). $('#windDir').html(result.data;weatherObservation,windDirection): } }, error, function(jqXHR; textStatus. errorThrown) { // your error code } }); } if (.load;weather) loadData3(). $('#timezoneRes');hide(). $('#oceanRes');hide(); $('#weatherRes').show(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <th>API Name</th> <th>API Description</th> <th></th> </tr> <tr> <td>1. Timezone</td> <td><p id="tabledescriptions">Description</p> <p>The timezone at the given longtitute and latitude.</p> <label for="longitude">Enter the Longitude: </label> <input type="text" id="long" name="longitude"> <label for="latitude">Enter the Latitude: </label> <input type="text" id="lat" name="latitude"> </td> <td><button id="buttonrun1">Submit</button></td> </tr> <tr> <td>2. Ocean Info</td> <td id=""><p id="tabledescriptions">Description</p> <p>The nearest Ocean to the longitude & latitude given above.</p> <label for="longitude1">Enter the Longitude: </label> <input type="text" id="long1" name="longitude1"> <label for="latitude1">Enter the Latitude: </label> <input type="text" id="lat1" name="latitude1"> </td> <td><button id="buttonrun2">Submit</button></td> </tr> <tr> <td>3. Weather ICAO</td> <td><p id="tabledescriptions">Description</p> <p>Display's the weather at a given Airport by its ICAO airport code.</p> <label for="ICAOCode">Enter ICAO Code</label> <select name="ICAOCode" id="selAirport"> <option value="yssy">Sydney Kingsford Smith International</option> <option value="egll">London Heathrow Airport</option> </select> </td> <td><button id="buttonrun3">Submit</button></td> </tr> <tr colspan="3"> <td id="timezoneRes"><p id="tabledescriptions">Result of Timezone API Call</p> <p>Sunrise:</p><p id="sunrise"></p> <p>Sunset:</p><p id="sunset"></p> <p>Country:</p><p id="country"></p> <p>Time Zone:</p><p id="timeZone"></p> <p>Time Now:</p><p id="timeNow"></p> </td> <td id="weatherRes"><p id="tabledescriptions">Result of Weather by ICAO Code Call</p> <p>Airport Name: </p><p id="airName"></p> <p>Wind Speed: </p><p id="windSp"></p> <p>Temperature (Celcius): </p><p id="temp"></p> <p>Wind Direction: </p><p id="windDir"></p> </td> <td id="oceanRes"><p id="tabledescriptions">Result of Ocean API Call</p> <p>Ocean: </p><p id="ocean"></p> </td> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM