javascript - html 和 php 文件返回为空
问题描述
我将文件分成 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
}
推荐阅读
- angularjs - AngularJS $routeProvider 不加载内容或从控制器登录到控制台
- tensorflow - 在 AWS SageMaker 上安装 Keras 和 TensorFlow
- bash - bash:参数扩展,使用默认值:当扩展已经被引用时,是否应该引用单词?
- file - SIP 呼叫是否有任何文件格式?
- java - 如何使用流将二维 int 数组转换为单个字符串?
- javascript - 使用PHP从MySQL获取JSON作为字符串,我们可以在字段中获取数据作为JSON
- javascript - 包含外部 js 文件仅在平板电脑上不起作用
- python - ModelDefinitionException("至少需要 1 个主键。") 即使已经定义了主键
- angularfire2 - 通过文档 ID 获取数据
- machine-learning - 首先在 SVD 之后对数据集执行 PCA 是否有意义?