如何实现AJAX来调用Web服务

时间:2015-12-18 20:38:36

标签: php ajax

我创建了一个简单的PHP界面,供用户输入国家/地区名称以了解当前天气。

这是我的php第一页,

<!DOCTYPE HTML>
<html>

<body>

  <h3>Current Weather</h3>
  <form action="currentWeather.php" method="post">
    <table>
      <tr>
        <td>Country Name:</td>
        <td>:
          <input type="text" name="countryName" />
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td align="right">
          <input type="submit">
        </td>
      </tr>
    </table>
  </form>

</body>

</html>

在该国家/地区的用户密钥后,它将在另一页上显示该国家/地区的天气状况。

<?php
        $countryName = $_POST["countryName"];

        $uri = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=" . $countryName . "&format=xml&num_of_days=5&key=ded6d9349e5334a39e2e2f26fd996";
        $weather = simplexml_load_file($uri);

        foreach ($weather->current_condition as $weatherinfo):
            $temp = $weatherinfo->temp_C;
            $icon = $weatherinfo->weatherIconUrl;
        endforeach;

        echo '<h2>Display the temperature and weather Icon</h2>';
        echo 'Current Temprarture ' . $temp . ' C <br>';
        echo " <img src = $icon >";
        echo '<br>';
 ?>

enter image description here

计划是用户点击提交按钮后,天气状况将显示在底部。

我尝试做一些研究,但我没有发现任何类似于我的问题。我目前正在调用一个名为world weather online的网络服务,不太确定如何用它实现AJAX。

1 个答案:

答案 0 :(得分:0)

尝试:

....
function myFunction() {
    xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            setTimeout("callback()", 3000);
        }
    }
    xmlHttp.open("GET", "url", true);
    xmlHttp.send();
};
function callback() {
    //xmlHttp.responseText
};
....