如何在JavaScript中将“获取”替换为“ ajax”方法?

时间:2019-12-24 03:11:48

标签: javascript jquery html ajax api

我现在正试图用ajax包住头,因为这是使用fetch检索数据。 语法大致相同,但是对它的外观感到好奇。


<head>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="searchContainer">
        <input class="searchControl" type="text" placeholder="City Name or Zipcode" id="searchInput">
        <button class="searchControl" id="searchBtn">Search</button>
    </div>
    <div id="weatherContainer">
        <div id="weatherDescription">
            <h1 id="cityHeader"></h1>
            <div id="weatherMain">
                <div id="temperature"></div>
                <div id="weatherDescriptionHeader"></div>
                <div><img id="documentIconImg"></div>
            </div>
            <hr>
            <div id="windSpeed" class="bottom-details"></div>
            <div id="humidity" class="bottom-details"></div>
        </div>
    </div>
    <script src="script.js" ></script>
</body>

这是我想从使用fetch方法转换为使用AJAX调用代替它的JavaScript。

---
let appId = 'b1e22f9b3891a9a6fc389e3e1a4cc496';
let units = 'imperial'; 
let searchMethod; 

function getSearchMethod(searchTerm) {
    if(searchTerm.length === 5 && Number.parseInt(searchTerm) + '' === searchTerm)
        searchMethod = 'zip';
    else 
        searchMethod = 'q';
}

function searchWeather(searchTerm) {
    getSearchMethod(searchTerm);
    fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`)
        .then((result) => {
            return result.json();
        }).then((res) => {
            init(res);
    });
}

function init(resultFromServer) {
    switch (resultFromServer.weather[0].main) {
        case 'Clear':
            document.body.style.backgroundImage = "url('clear.jpg')";
            break;

        case 'Clouds':
            document.body.style.backgroundImage = "url('cloudy.jpg')";
            break;

        case 'Rain':
        case 'Drizzle':
        case 'Mist':
            document.body.style.backgroundImage = "url('rain.jpg')";
            break;

        case 'Thunderstorm':
            document.body.style.backgroundImage = "url('storm.jpg')";
            break;

        case 'Snow':
            document.body.style.backgroundImage = "url('snow.jpg')";
            break;

        default:
            break;
    }

    let weatherDescriptionHeader = document.getElementById('weatherDescriptionHeader');
    let temperatureElement = document.getElementById('temperature');
    let humidityElement = document.getElementById('humidity');
    let windSpeedElement = document.getElementById('windSpeed');
    let cityHeader = document.getElementById('cityHeader');

    let weatherIcon = document.getElementById('documentIconImg');
    weatherIcon.src = 'http://openweathermap.org/img/w/' + resultFromServer.weather[0].icon + '.png';

    let resultDescription = resultFromServer.weather[0].description;
    weatherDescriptionHeader.innerText = resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1);
    temperatureElement.innerHTML = Math.floor(resultFromServer.main.temp) + '&#176;';
    windSpeedElement.innerHTML = 'Winds at  ' + Math.floor(resultFromServer.wind.speed) + ' m/s';
    cityHeader.innerHTML = resultFromServer.name;
    humidityElement.innerHTML = 'Humidity levels at ' + resultFromServer.main.humidity +  '%';

    setPositionForWeatherInfo();
}

function setPositionForWeatherInfo() {
    let weatherContainer = document.getElementById('weatherContainer');
    let weatherContainerHeight = weatherContainer.clientHeight;
    let weatherContainerWidth = weatherContainer.clientWidth;

    weatherContainer.style.left = `calc(50% - ${weatherContainerWidth/2}px)`;
    weatherContainer.style.top = `calc(50% - ${weatherContainerHeight/1.3}px)`;
    weatherContainer.style.visibility = 'visible';
}

document.getElementById('searchBtn').addEventListener('click', () => {
    let searchTerm = document.getElementById('searchInput').value;
    if(searchTerm)
        searchWeather(searchTerm);
});
---

如果有人有任何想法或知道100%有效的解决方案,请随时分享。不知道该怎么办。

1 个答案:

答案 0 :(得分:3)

编辑: :这个答案有误吗?不确定为什么要投票?嘘.....

fetch$.ajax是到同一目的地的不同路由。他们都轻松表现得像XMLHttpRequest。.

我建议坚持使用fetch,因为它得到了 默认 的广泛支持,比XMLHttpRequest更易于使用,并且不需要任何第三方图书馆。要使用$.ajax,(据我所知),您必须导入jQuery-与$.ajax一起导入很多不必要的代码。如果您可以在没有第三方库的情况下进行操作,则应该这样做。

话虽如此,使用$.ajax看起来像这样:

特定功能:

function searchWeather(searchTerm) {
  getSearchMethod(searchTerm);
  $.ajax({
    url: `https://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`,
    success: (data) => {
      init(data);
    },
    failure: (err) => {
      console.log("ERROR!", err);
    }
  });
}

演示:

let appId = "b1e22f9b3891a9a6fc389e3e1a4cc496";
let units = "imperial";
let searchMethod;

function getSearchMethod(searchTerm) {
  if (searchTerm.length === 5 && Number.parseInt(searchTerm) + "" === searchTerm)
    searchMethod = "zip";
  else searchMethod = "q";
}

function searchWeather(searchTerm) {
  getSearchMethod(searchTerm);
  $.ajax({
    url: `https://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`,
    success: (data) => {
      init(data);
    },
    failure: (err) => {
      console.log("ERROR!", err);
    }
  })
    /*
    fetch(`https://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`)
    .then(result => {
      return result.json();
    })
    .then(res => {
      init(res);
    });
    */
}

function init(resultFromServer) {
  switch (resultFromServer.weather[0].main) {
    case "Clear":
      document.body.style.backgroundImage = "url('clear.jpg')";
      break;

    case "Clouds":
      document.body.style.backgroundImage = "url('cloudy.jpg')";
      break;

    case "Rain":
    case "Drizzle":
    case "Mist":
      document.body.style.backgroundImage = "url('rain.jpg')";
      break;

    case "Thunderstorm":
      document.body.style.backgroundImage = "url('storm.jpg')";
      break;

    case "Snow":
      document.body.style.backgroundImage = "url('snow.jpg')";
      break;

    default:
      break;
  }

  let weatherDescriptionHeader = document.getElementById(
    "weatherDescriptionHeader"
  );
  let temperatureElement = document.getElementById("temperature");
  let humidityElement = document.getElementById("humidity");
  let windSpeedElement = document.getElementById("windSpeed");
  let cityHeader = document.getElementById("cityHeader");

  let weatherIcon = document.getElementById("documentIconImg");
  weatherIcon.src =
    "http://openweathermap.org/img/w/" +
    resultFromServer.weather[0].icon +
    ".png";

  let resultDescription = resultFromServer.weather[0].description;
  weatherDescriptionHeader.innerText =
    resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1);
  temperatureElement.innerHTML =
    Math.floor(resultFromServer.main.temp) + "&#176;";
  windSpeedElement.innerHTML =
    "Winds at  " + Math.floor(resultFromServer.wind.speed) + " m/s";
  cityHeader.innerHTML = resultFromServer.name;
  humidityElement.innerHTML =
    "Humidity levels at " + resultFromServer.main.humidity + "%";

  setPositionForWeatherInfo();
}

function setPositionForWeatherInfo() {
  let weatherContainer = document.getElementById("weatherContainer");
  let weatherContainerHeight = weatherContainer.clientHeight;
  let weatherContainerWidth = weatherContainer.clientWidth;

  weatherContainer.style.left = `calc(50% - ${weatherContainerWidth / 2}px)`;
  weatherContainer.style.top = `calc(50% - ${weatherContainerHeight / 1.3}px)`;
  weatherContainer.style.visibility = "visible";
}

document.getElementById("searchBtn").addEventListener("click", () => {
  let searchTerm = document.getElementById("searchInput").value;
  if (searchTerm) searchWeather(searchTerm);
});
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div id="searchContainer">
    <input class="searchControl" type="text" placeholder="City Name or Zipcode" id="searchInput">
    <button class="searchControl" id="searchBtn">Search</button>
  </div>
  <div id="weatherContainer">
    <div id="weatherDescription">
      <h1 id="cityHeader"></h1>
      <div id="weatherMain">
        <div id="temperature"></div>
        <div id="weatherDescriptionHeader"></div>
        <div><img id="documentIconImg"></div>
      </div>
      <hr>
      <div id="windSpeed" class="bottom-details"></div>
      <div id="humidity" class="bottom-details"></div>
    </div>
  </div>
  <script src="script.js"></script>
</body>