[英]Copy external json data and paste in local json file
我的管理界面上有一堆小部件,其中之一是天气。 根据我的管理界面的编码方式,它每60秒重新加载一次。 对于天气情况,每分钟api调用过多。 仅更改天气小部件的刷新率会花费很多,因此,如果我每隔60分钟从openweathermap.org复制数据并将数据放置在我的weatehr小部件可以访问的本地json中,则会更容易对外部源进行了许多api调用。
我如何使用jquery,javascript或php将如下所示的数据从网站地址复制到本地JSON文件?
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":296.2,"pressure":1023,"humidity":69,"temp_min":294.82,"temp_max":297.15},"wind":{"speed":1.5},"clouds":{"all":75},"dt":1473178865,"sys":{"type":1,"id":5091,"message":0.0074,"country":"GB","sunrise":1473139361,"sunset":1473186795},"id":2643743,"name":"London","cod":200}
我建议您创建一个计划任务,该任务每60秒钟运行一次,以通过api获取天气数据,然后将数据存储到本地文件中,并重定向管理界面以从该文件(而不是api)读取
您可以使用cron作业来创建计划任务,以从api检索数据。
这是使用PHP从api检索天气数据并将结果存储到文本文件的示例代码。
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=79191467e423ba376b1b72529788eeb8",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$weather_data = ($response);
// save $weather_data to local file
$file = 'weather_data.txt';
// Write the contents to the file
file_put_contents($file, $weather_data);
}
也许您想使用一个书签:
javascript:(function() {
function httpGet()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var theUrl = "http://api.openweathermap.org/data/2.5/weather?q=London";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
saveTextAsFile(xmlhttp.responseText);
};
};
xmlhttp.open("GET", theUrl, false );
xmlhttp.send();
}
function saveTextAsFile(textToSave )
{
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = "weather.json";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
httpGet();
})();
只需在加载http://api.openweathermap.org之后调用它(或将其加载到代码中即可。),然后在脚本的url中添加API密钥...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.