如何写回复文件?

时间:2017-12-26 18:05:30

标签: javascript php

此脚本的输出在浏览器中很好。我测试了自己并得到了准确的结果。我想知道的是,如何将响应写入文件?我尝试编写响应,我得到的是编写的代码而不是输出。

<?php

$loc = '<body onload="getLocation()">
<p id="demo"></p>

<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
} else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + 
"<br>Longitude: " + position.coords.longitude;
}
</script>';

//File Write
echo $loc;
$log = fopen("loc.txt", "a");
$info = "$loc\n";
fwrite($log, $info);
fclose($log);

?>

输出=浏览器的GPS坐标

1 个答案:

答案 0 :(得分:-1)

您可以尝试沿着这些方向行事 - 未经测试,以便可能出现错误!我建议你不要回复身体标签,就像你这样......

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['lat'], $_POST['lng'] ) ){
        ob_clean();
        $bytes = file_put_contents('loc.txt',json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
        exit( $bytes ? 'ok' : 'bad foo' );
    }




    $loc = '<body onload="getLocation()"><p id="demo"></p>
    <script>

        var x = document.getElementById("demo");

        function ajax(url,callback,payload){
            var xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if( this.status==200 && this.readyState==4 )callback.call(this,this.response)
            }
            xhr.open("POST",url,true);
            xhr.send( payload );
        }
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
            } else { 
                x.innerHTML = "Geolocation is not supported by this browser.";
            }
        }

        function showPosition( position ) {
            x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
            ajax.call( this, location.href, function(r){
                alert(r)
            }, 'lat='+position.coords.latitude+'&lng=' + position.coords.longitude );
        }
    </script>';

    echo $loc;
?>