Почему функция Ajax не отвечает на событие нажатия кнопки - PullRequest
0 голосов
/ 25 сентября 2019
$(document).ready(function() {
  $.ajax({
    url: "https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=09e7a4e8ee418a607b4fcec06929900e",
    async: true,
    type: "GET",
    datatype: "json",
    success: function(data) {
      $("#weather").text(Math.floor(data.main.temp - 273.15) + decodeURI('%C2%B0') + "C") ///Add the weather from api
      $("#location").text(data.name);
      $('#Status').text(data.weather[0].main)
      if (data.weather[0].icon == "10n") {
        var imgurl = "/Images/showerrain.jpg"
        $('#Weather-Header').css('background-image', 'url(https://media.giphy.com/media/t7Qb8655Z1VfBGr5XB/giphy.gif)', 'background-size', 'cover', 'background-repeat', 'no-repeat');
      }
      console.log(data)
    },
    error: function(ex) {

      console.log("Error");
    }
  });
});

Когда я вызываю ajax через document.ready, он работает нормально, когда я вызываю тот же ajax в событии нажатия кнопки, он не отвечает даже с ошибкой.*

$(document).ready(function() {
  $("#Searchbut").click('click', function() {
    $.ajax({
      url: "https://api.openweathermap.org/data/2.5/weather?q=Chennai&APPID=09e7a4e8ee418a607b4fcec06929900e",
      async: true,
      type: "GET",
      datatype: "json",
      success: function(data) {
        $("#weather").text(Math.floor(data.main.temp - 273.15) + decodeURI('%C2%B0') + "C") ///Add the weather from api
        $("#location").text(data.name);
        $('#Status').text(data.weather[0].main)
        if (data.weather[0].icon == "10n") {
          var imgurl = "/Images/showerrain.jpg"
          $('#Weather-Header').css('background-image', 'url(https://media.giphy.com/media/t7Qb8655Z1VfBGr5XB/giphy.gif)', 'background-size', 'cover', 'background-repeat', 'no-repeat');
        }
        alert(data);
      },
      error: function(ex) {

        console.log("Error");
      }

    });
  });
});

1 Ответ

0 голосов
/ 25 сентября 2019

Аргумент, переданный функции щелчка, неверен.Метод click () запускает событие click или присоединяет функцию, запускаемую при возникновении события click.

SYNTAX

Инициирует событие click для выбранных элементов:

$(selector).click()

Присоединение функции к событию щелчка:

$(selector).click(function)

Вы также можете использовать метод on () .Метод on () присоединяет один или несколько обработчиков событий для выбранных элементов и дочерних элементов.

Следовательно, вы можете сделать это

$(document).ready(function () {

      $("#Searchbut").on('click', function () {

          $.ajax({
              url: "https://api.openweathermap.org/data/2.5/weather?q=Chennai&APPID=09e7a4e8ee418a607b4fcec06929900e",
              async: true,
              type: "GET",
              dataType: "json",
              success: function (data) {
                  $("#weather").text(Math.floor(data.main.temp - 273.15) + decodeURI('%C2%B0') + "C")///Add the weather from api
                  $("#location").text(data.name);
                  $('#Status').text(data.weather[0].main)
                  if (data.weather[0].icon == "10n") {
                      var imgurl = "/Images/showerrain.jpg"
                      $('#Weather-Header').css('background-image', 'url(https://media.giphy.com/media/t7Qb8655Z1VfBGr5XB/giphy.gif)', 'background-size', 'cover', 'background-repeat', 'no-repeat');
                  }
                  alert(data);
              },
              error: function (ex) {

                  console.log("Error");
              }

          });
      });

ИЛИ

$(document).ready(function () {

      $("#Searchbut").click(function () {

          $.ajax({
              url: "https://api.openweathermap.org/data/2.5/weather?q=Chennai&APPID=09e7a4e8ee418a607b4fcec06929900e",
              async: true,
              type: "GET",
              dataType: "json",
              success: function (data) {
                  $("#weather").text(Math.floor(data.main.temp - 273.15) + decodeURI('%C2%B0') + "C")///Add the weather from api
                  $("#location").text(data.name);
                  $('#Status').text(data.weather[0].main)
                  if (data.weather[0].icon == "10n") {
                      var imgurl = "/Images/showerrain.jpg"
                      $('#Weather-Header').css('background-image', 'url(https://media.giphy.com/media/t7Qb8655Z1VfBGr5XB/giphy.gif)', 'background-size', 'cover', 'background-repeat', 'no-repeat');
                  }
                  alert(data);
              },
              error: function (ex) {

                  console.log("Error");
              }

          });
      });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...