首页 > 解决方案 > 在 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>

标签: javascriptphphtml

解决方案


推荐阅读