douxuan0698 2014-05-25 05:43
浏览 25
已采纳

通过Javascript获取地理位置,并通过PHP将其保存到文本文件

I want to get latitude and longitude of the guest and save them to a text file..

I used this:

<html>
<body>

<?php

 $location = print '
   <SCRIPT LANGUAGE="JavaScript">
window.onload=function(){
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(pos){
document.write("Location: "+pos.coords.latitude+","+pos.coords.longitude);
</script>
'

;



$Seb = "*******************" ;
 $file = "save.txt";
 $a = fopen($file, "a");
 fwrite($a,$location."
");
    fwrite($a,$Seb."
");
 fclose($a);


?>
<form action="index.php">
<input type="submit" value="Refresh">
</form>


</body>
</html>

but the result in the text file is :

1

with out any geolocation data

Any Help please?

  • 写回答

1条回答 默认 最新

  • dtdh11647 2014-05-25 05:51
    关注

    This is totally not how it works. As javascript is client-side, and PHP is server-side, you can't just do it the way you are trying to. You need to send that information to the server from client browser. The most common way, would be using ajax to POST javascript generatred content...

    With jQuery it would be as easy as:

    In html file...

    <script>
    window.onload=function(){
    if(navigator.geolocation)
    {
      navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
      alert("Geolocation is not supported by this browser.");
    }
    }
    function showPosition(pos){
       $.post('saver.php',{'lat':pos.coords.latitude,'lng':pos.coords.longitude},function(res){
          console.log(res);
       });
    }
    </script>
    

    In saver.php

    <?php
       print_r($_POST);
       $a = fopen("save.txt", "a");
       fwrite($a,"Location: $_POST[lat],$_POST[lng]
    *******************
    ");
       fclose($a);
    ?>
    

    PS. If you can't or don't want to use jQuery, please check this answer for information on how to use ajax in raw javascript.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料