(F)在 html 文件中使用 get 中的 post 写入访问者的地理坐标

(F)write in a html file to the visitor's geo-coordinates using a post inside a get

我正在处理坐标。我不想使用 GeoIP 数据库。所以我首先尝试获取坐标,然后将它们与 post 一起发送到 php 文件,该文件将它们写入 html 文件。 这是 index.html 代码:

<p> Hello. </p>

<script type="text/javascript">

$.get("http://ipinfo.io", function (response) {
var ip = response.ip;
var city = response.city;
var region = response.region;
var details = JSON.stringify(response, null, 4); 

  $.ajax({
    type: "POST",
    url: 'write.php', 
    data: '&ip='+ ip + '&city=' + city +  '&region=' + region +  '&details=' + details,
    success: function (data) {   
      alert("Sent!");
    },
    error: function(jqXHR, text, error){ 
       alert("Error: not sent.");       
      }
  }); 

}, "jsonp");

这是 write.php 代码:

<?php 

    $ip = $_POST['ip'];
    $city = $_POST['city'];
    $region = $_POST['region'];
    $details = $_POST['details']; 

$fh = fopen('lol.html', 'a') or die("can't open file");

fwrite($fh,'IP: $ip ;');
fwrite($fh,'Details: $details'); 

fclose($fh);

echo "Created";
?> 

如果我托管并打开 index.html,它会提醒 "Sent!"。但是,当我打开 lol.html 时,我看到了字符串:IP: $ip ;Details: $details

为什么?我究竟做错了什么?

这是因为您在写入数据时试图在单引号内使用变量';所以变量没有得到评估,而是被视为文字。

所以,试试这个:

<?php 

// Parse input
$ip      = isset($_POST['ip'])      ? $_POST['ip']      : '';
$city    = isset($_POST['city'])    ? $_POST['city']    : '';
$region  = isset($_POST['region'])  ? $_POST['region']  : '';
$details = isset($_POST['details']) ? $_POST['details'] : ''; 

// Open file for writing
$fh = @fopen('lol.html', 'a');
if (!$fh) exit('Failed to open file for writing')

// Write data
fwrite($fh, "IP: $ip\r\n");
fwrite($fh, "Details: $details"); 

// Finished
fclose($fh);
echo "Created";

?>

更新

根据您的意见,我将此脚本优化为以下内容,试试看:

index.html(或任何 .html 文件)

<p> Hello. </p>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">

$.getJSON('http://ipinfo.io', function(response) {
    $.post('write.php', { response: JSON.stringify(response) })
    .done(function(result) {
        alert(result);
    });
});

</script>

write.php

<?php 

// Parse input
$response = isset($_POST['response']) ? $_POST['response'] : '';

// Decode input
$response = @json_decode($response, true);
if (!$response) {
    exit('Invalid input.');
}

// Open file for writing
$fh = @fopen('lol.html', 'a');
if (!$fh) {
    exit('Failed to open file for writing.');
}

// Write data
$result = '<pre>';
foreach ($response as $key => $value) {
    $result .= "$key = $value\r\n";
}
$result .= '</pre>';
fwrite($fh, $result);

// Finished
fclose($fh);
echo "Created";

?>

生成的 lol.html 文件现在将如下所示(当执行 index.html 时):

<pre>ip = 90.152.2.38
hostname = host90-152-2-38.ipv4.regusnet.com
city = St Albans
region = England
country = GB
loc = 51.8379,-0.4399
org = AS8220 COLT Technology Services Group Limited
postal = AL3
</pre>

如果您在浏览器中打开此 lol.html 文件,它将呈现如下:

这就是你想要的吗?