简体   繁体   中英

Populate URL dynamically from Form Field

I have an HTML file that uses an AJAX script to access an API. I would like to include a form field to allow a user to enter an Airport ID. When submitting I'd like to place this ID appropriately/dynamically in the ajax url. If no ID is found then default the URL to use KCLT Logic will need to be around line 70 (See comments in code).

I have two versions of the file. The.html version listed below or click here , the.PHP version can be found here .

Excerpt from where logic should go

// GET Icao From QueryString if Avilable if Not then Default to KCLT. The URL must look like the one listed below for the API call to work.


url: 'https://api.checkwx.com/metar/KCLT/radius/50/decoded/?include=1',

Full Page Code Here

<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Simple example of using jQuery to display METAR weather from api.checkwx.com">

  <title>METAR Weather Example</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>

<body>

  <div class="container mt-5">

    <form action="/metar_example.html" method="get">
      <label for="fname">Icao:</label>
      <input type="text" id="icao" name="icao"><input type="submit" value="Submit">
    </form>

    <h2>METAR</h2>
    <h4><span id="icao"></span> <span id="name"></span></h4>
    <hr>
    <pre id="raw"></pre>
    <hr>
    <h3><pre id="category"></pre></h3>
    <h5>Altimeter: </h5><pre id="alt"></pre>

    <div id="wind_block" class="d-none">
      <h5>Wind</h5>
      <ul>
        <li>
          <span id="wind_direction"></span> @ <span id="wind_speed"></span><small> knots, Gusts: </small><span id="wind_gusts"></span>
        </li>
      </ul>
    </div>

    <div id="visibility_block" class="d-none">
      <h5>Visibility</h5>
      <ul>
        <li>
          <span id="visibility_miles"></span><small> miles</small>
        </li>
      </ul>
    </div>

    <div id="cloud_block" class="d-none">
      <h5>Clouds</h5>
      <ul id="cloud_list">
      </ul>
    </div>

    <div id="cond_block" class="d-none">
      <h5>Conditions</h5>
      <ul id="cond_list">
      </ul>
    </div>

  </div>

</body>

<script>
  $.ajax({
    type: 'GET',
    // GET Icao From QueryString if available if not then default to KCLT. The URL must look like the one listed below for the API call to work.


    url: 'https://api.checkwx.com/metar/KCLT/radius/50/decoded/?include=1',

    // You must supply your own X-API-Key from api.checkwx.com
    headers: {
      'X-API-Key': 'xxx'
    },
    dataType: 'json',
    error: function (response) {
      var e = response.responseJSON;
      $('#icao').text(e.statusCode);
      $('#name').text(e.error);
      $('#raw').text(e.message);
    },
    success: function (response) {
      if (response.results > 0) {
        // We only requested one METAR
        // If you request more than one, the data array would need to be in a loop
        var metar = response.data[0];

        $('#icao').text(metar.icao);
        $('#name').text(metar.station.name);
        $('#raw').text(metar.raw_text);
        $('#category').text(metar.flight_category);
        $('#alt').text(metar.barometer.hg);

        if (metar.visibility) {
          $('#visibility_miles').text(metar.visibility.miles);
          $('#visibility_block').removeClass('d-none');
        }


        if (metar.wind) {
          $('#wind_direction').text(metar.wind.degrees);
          $('#wind_speed').text(metar.wind.speed_kts);
          $('#wind_gusts').text(metar.wind.gust_kts);
          $('#wind_block').removeClass('d-none');
        }

        if (metar.clouds[0]) {
          $('#cloud_block').removeClass('d-none');
          metar.clouds.forEach(cloud => {
            $("#cloud_list").append('<li>' + cloud.text + ' at ' + cloud.base_feet_agl +
              ' <small> feet AGL</small></li>');

          });
        }

        if (metar.conditions[0]) {
          $('#cond_block').removeClass('d-none');
          metar.conditions.forEach(cond => {
            $("#cond_list").append('<li>' + cond.text + '</li>');

          });
        }
      } else {
        $('#raw').text('No results returned from API');
      }
    }
  });
</script>

</html>

Add an ID to your HTML form, so we can reference it easily - for example, icao_form :

<form id="icao_form" action="/metar_example.html" method="get">

Create a submit function which handles the form, to replace the default non-Ajax action - for example:

$("#icao_form").submit(function(event){
  event.preventDefault(); // prevent the default form submit action
  var airportID = $('#icao').val();
  if (airportID.length == 0) {
    airportID = "KCLT";
  }
  // use a JS template literal here:
  url = `https://api.checkwx.com/metar/${airportID}/radius/50/decoded/?include=1`
  console.log(url); // for testing/demonstration

  // add your existing ajax call here...

});

Finally, you would need to add your existing $.ajax({...}); inside this submit function - and remove the existing URL variable, since that is already handled in the above code. You may prefer to put you ajax code in a function and then call the function in the above code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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