$ .ajax在立即调用时有效,但在单击时作为回调调用时不起作用

时间:2019-02-24 15:54:45

标签: jquery ajax

当在页面加载时自行调用getWeather()时,API调用以及将响应写入DOM的工作原理。但是,如果我单击一次按钮调用getWeather,则什么也不会发生(控制台中没有错误)。

  const submitButton = document.querySelector('input[type="submit"]');
  const max = document.querySelector('.max');

  getWeather = () => {   
    $.ajax(weatherEndpoint)
       .then(function(response) {
          //response  
          const maxTemp = response.main.temp_max;
          //write response to DOM
          max.innerText = maxTemp;
        });
      }

  //this works:        
  getWeather()  

 //this does not work:
 //submitButton.addEventListener("click", getWeather ) 

2 个答案:

答案 0 :(得分:1)

由于您使用的是jquery,因此可以只使用click()将事件附加到按钮:

$(submitButton).click(function(e) {
    e.preventDefault();
    getWeather();
});

如果submitButton是表单,并且是type="submit",那么它将把表单提交给服务器。要停止使用,请使用e.preventDefault();

您应该可以将其添加到您的代码中

getWeather = (e) => {  
    e.preventDefault(); 
    $.ajax(weatherEndpoint)
       .then(function(response) {
          //response  
          const maxTemp = response.main.temp_max;
          //write response to DOM
          max.innerText = maxTemp;
    });
}

并致电submitButton.addEventListener("click", getWeather );

答案 1 :(得分:0)

您提到的

multipart/related; boundary=boundary53170215682661314146

从下面尝试

//this does not work:
 //submitButton.addEventListener("click", getWeather )  

然后删除该行

$('input[type="submit"]').click(getWeather);
相关问题