我的ajax.php脚本
<?php
$lat =$_POST['lat'];
$lon = $_POST['lon'];
echo $lat;
echo $lon;
?>
还有我的 new.html 页面
<!DOCTYPE html>
<html><head><script src="jquery-1.12.0.min.js"></script>
</head>
<body>
<p>Click the button to get your coordinates.</p>
<input type="text" name="metin"/><br/>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var x = document.getElementById("demo");
var y = document.getElementById("demo1");
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;
var lon= position.coords.longitude;
var lat= position.coords.longitude;
y.innerHTML=lon;
x.innerHTML=lat;
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { lat:lat, lon:lon}
success: function(result) {
$('#sonuc').html(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
}
}
</script>
<p id="sonuc"></p>
</body>
</html>
首先我知道有未使用的代码。但我要使用这个 block 。 它没有给我任何回应。它必须成功地工作。 但它没有在我的 php 页面中提供经纬度变量。 如果有其他方法将变量发送到 php 页面我可以尝试。
最佳答案
代码中没有功能问题。但有一些语法错误阻止了ajax请求。
- 避免在函数 showPosition() 下方使用额外的右大括号。
- 在ajax请求的数据部分后添加逗号。
下面给出了更正的代码。
<script>
var x = document.getElementById("demo");
var y = document.getElementById("demo1");
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;
var lon= position.coords.longitude;
var lat= position.coords.longitude;
y.innerHTML=lon;
x.innerHTML=lat;
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { lat:lat, lon:lon},
success: function(result) {
$('#sonuc').html(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
}
</script>
关于javascript - Jquery ajax将变量发布到php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389742/