javascript - 在 PHP 中为网站调用 JavaScript 函数
问题描述
首先,感谢您甚至花时间查看我的问题。
我创建了一个程序,在获取他们的 IP 地址时使用 API 显示用户的当地天气、时间和位置。当我有一个 .html 文件时,代码工作得非常好,但是因为我想把它放在一个网站上,所以我把它变成了一个 .php 文件,我将把它包含在我的其他 php 文件中。
一旦我将文件的扩展名更改为 .php,我的代码就会停止工作。我是编程新手,所以希望你能理解为什么,因为我没有取得任何成功。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<style>
body {
font-family:'Courier New', Courier, monospace
}
p {
display: inline;
}
#fps
{
display: inline;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var cityOut = document.getElementById('city');
fetch('http://ip-api.com/json/')
.then( res => res.json())
.then(response => {
cityOut.innerHTML = response.city + ', ' + response.country;
})
.catch((data, status) => {
console.log('Request failed');
})
var fpsOut = document.getElementById('fps');
setInterval(function () {
var d = new Date();
fpsOut.innerHTML = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
}, 1000);
navigator.geolocation.getCurrentPosition(success);
});
function success(pos) {
var weather = document.getElementById('weather');
var crd = pos.coords;
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
fetch('https://fcc-weather-api.glitch.me/api/current?lat='+crd.latitude+'&lon='+crd.longitude)
.then( res => res.json())
.then(response => {
weather.innerHTML = response.main.temp;
})
.catch((data, status) => {
console.log('Request failed');
})
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body>
<p>Current Local Time:</p>
<div id="fps"></div>
<div id="city"></div>
<div id="weather"></div>
</div>
</body>
</html>
解决方案
推荐阅读
- c++ - 如何有条件地实例化具有多个模板参数的模板类?
- reactjs - 渲染到带有上下文的字符串?
- java - 我在以下程序中得到 OptionalDataException。为什么会出现这个错误
- android - 如何处理 UI 中的数据库事务延迟以提供良好的用户体验?
- c++ - 将自定义对象添加到向量时如何启用移动语义?
- java - 在 Kafka Consumer 中反序列化 Avro 数据包时出现堆空间问题
- python - python中XGBoost中关于predict_proba函数的问题
- c# - Microsoft graph c# sdk如何将用户分配给应用程序
- scala - 重置与 Url/Port 的连接 - 如果在过去 N 分钟内未收到任何数据
- angular - 仅在我查找 3 个字符时显示表格