gpt4 book ai didi

javascript - html 和 php 文件返回空

转载 作者:行者123 更新时间:2023-12-03 01:57:05 25 4
gpt4 key购买 nike

我将文件分为 geolocation.html 和 test.php。我使用 Ajax 传递变量 var latitude 和 longitude 以在我的 php 文件中使用,但两者都返回空。并不真正需要 div 只是希望能够在我的 php 文件中使用经度和纬度。我需要在我的成功函数中添加一些内容,进行函数调用吗?我缺少什么?地理定位.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type= "text/javascript" src= "js/jquery.js" > </script>
<script>

//javascript is on the client
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.write("Geolocation is not supported by this browser.");
}
}


function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

//Pass longitude and latitude to php how?
$.ajax({
type: 'POST',
url: 'test.php',
data: {lat: latitude,lng:longitude},
success: function(data) {
/*Pass longitude and latitude to php*/
$("#content").html(data);
}
});
}

</head>
<body onload="getLocation()">
<div id="content"></div>
</body>

现在是test.php文件

<?php 
// $addlat = $_GET['addlat'];
// $addlong = $_GET['addlong'];
if (isset($_POST['lat']) && isset($_POST['lng']) ) {
$lat = $_POST['lat'];
$lng = $_POST['lng'];
echo $lat." ".$lng ;
}
?>

最佳答案

尝试下面的代码

HTML/PHP 文件

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(redirectToPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function redirectToPosition(position) {
//window.location='weather.php.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;

$.ajax({
url: 'vuetest/testajax',
type: 'POST',
data: {lat: position.coords.latitude, lng: position.coords.longitude},
success : function(resp) {
console.log(resp)
}
})

}
</script>

</body>
</html>

服务器端

public function testajax()
{
print_r($_POST);
// Here you can check and use variables
}

关于javascript - html 和 php 文件返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50187098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com