jquery - 将点击事件更改为页面加载
问题描述
我有一个天气 api 的演示代码。我需要将它从点击事件更改为在页面打开时加载。我该怎么做。我对 jquery 还很陌生。欢迎任何帮助
function bclicked()
{
//This function was for testing my button and containers
console.log("CLICKED!");
var node = document.createElement("P");
var textnode = document.createTextNode("Placeholder for real weather!");
node.appendChild(textnode);
document.getElementById("weather").innerHTML = "";
document.getElementById("weather").appendChild(node);
}
function getweather()
{
//Does a post request for the ZIP entered to the API
console.log("REQUESTING WEATHER");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200) {
var weather = JSON.parse(this.responseText);
console.log(weather);
maketable(weather); //Generates content
}
else
{
console.log("this.readyState=",this.readyState);
console.log("this.status=",this.status);
}
};
var dataprefix = "https://api.openweathermap.org/data/2.5/weather?zip=33431,us"
var datasuffix = "&units=imperial&appid=925e764bc4519818e577ebdbae087ef8"
var data = dataprefix + document.getElementById.value + datasuffix;
console.log("requesting:",data);
xmlhttp.open("POST", data, true)
xmlhttp.send();
}
解决方案
删除该函数bclicked()
,然后调用getweather()
如下。这将getweather()
在页面加载时调用函数。
getweather();
function getweather()
{
// function body
}
推荐阅读
- python - 在 Linux 服务器 Centos 上安装 Python ODBC (pyodbc) 失败
- java - 无法为 JLabel 设置垂直文本位置?
- php - 这是不是一个数组?
- delphi - 如何使用delphi从json中获取值
- escaping - Logstash-文件输入添加转义
- c# - 如何停止处于等待用户请求状态的线程
- node.js - 将 json 值转换为 var
- wcf - WCF抛出服务器拒绝客户端凭据的异常,WCF中NetTCP的默认安全模式是什么
- android - Android - 导入 AAR 时出错,错误:找不到属性
- android - 无法解决资源链接失败错误