从AJAX代码正确地将值传递给PHP

时间:2017-03-09 15:57:49

标签: php jquery html ajax api

所以我试图将我的AJAX代码中的值传递给我的PHP代码,该代码连接到API以获取天气。它只在使用PHP时工作,但我希望ajax将结果返回到同一页面上的某个div。当我将其与其他示例进行比较时,我的代码看起来是正确的,但它只是无法正常工作。

代码可能没有考虑到安全性,标准做法等,我只是尝试使用API​​并获得AJAX的基础知识。 api.php:     

  $city = $_POST['city'];

  function getCityLat($x) {
    $latUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $x .'APIKEY';

    $latResponse = file_get_contents($latUrl);
    $latArray = json_decode($latResponse, true);

    $lat = $latArray['results'][0]['geometry']['location']['lat'];
echo $lat;
    return $lat;
  }

  function getCityLng($y) {
    $lngUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $y .'APIKEY';

    $lngResponse = file_get_contents($lngUrl);
    $lngArray = json_decode($lngResponse, true);

    $lng = $lngArray['results'][0]['geometry']['location']['lng'];

    echo $lng;
    return $lng;
  }

  function getWeather($x, $y) {
    $weatherUrl = 'https://api.darksky.net/forecast/APIKEY/' . $x . ',' . $y;
    $weatherResponse = file_get_contents($weatherUrl);

    $weatherArray = json_decode($weatherResponse, true);

    $timeZone = $weatherArray['timezone'];
    $locWeather = $weatherArray['currently']['temperature'];
    $locFeelsLike = $weatherArray['currently']['apparentTemperature'];
    $windSpeed = $weatherArray['currently']['windSpeed'];
    $weatherSummary = $weatherArray['currently']['summary'];
    $time = $weatherArray['currently']['time'];

    $outputweather = '<p>Temp: '.$locWeather.'</p>';
    echo $outputweather;
  }

  getWeather(getCityLat($city), getCityLng($city));

?>

的index.php(HTML):

<h3 align="center">Weather</h3>
    <form align="center" method="POST">
      <input type="text" id="city" name="city" placeholder="Enter City">
      <button class="btn btn-xs btn-success" name="city_go" id="city_go">Go</button>
    </form>
  <div id="weather"></div>

JQuery的:

function getWeather(city) {
    $.ajax({
      url: "api.php",
      method: "POST",
      data: {city:city}, 
      dataType: "text",
      success: function(data) {
        $('#weather').html(data);
      }
    });
  }

   $(document).on('click', '#city_go', function() {
    var city = $('#city').val();
    getWeather(city);
  });

1 个答案:

答案 0 :(得分:0)

问题是您提交的表单会强制刷新页面。其他一切正常,只是页面正在刷新。要解决此问题,您需要将点击事件更新为

$(document).on('click', '#city_go', function(e) {
    e.preventDefault();
    var city = $('#city').val();
    getWeather(city);
});

preventDefault()调用将取消表单的默认操作(页面刷新),并允许AJAX调用跟进并显示数据。