>im 试图将 ajax 响应存储到 Post php 变量,然后在同一页面上回显它,但遗憾的是,它返回"注意:未定义的索引"
我认为这与 ajax 的成功部分有关。你能帮我纠正一下吗?
提前感谢:)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<form action="" method="post">
<input type="submit" name="ido" value="Click" /></td>
</form>
<script>
var x=document.getElementById("log");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="GPS szolgáltatás nem müködik ezen a böngészőn, kérlek értesítsd a rendszergazdát!";}
}
function showPosition(position)
{
navigator.geolocation.getCurrentPosition(showPosition);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url: "test.php",
type: 'POST', //I want a type as POST
data: {'name' : latitude },
success: function(response) {
alert(response);
}
});
}
</script>
<?php
if(isset($_POST["ido"])){
echo "<script>getLocation();</script>";
$name=$_POST["name"];
print_r($_POST);
}
?>
</html>
首先,您的 DOCTYPE 声明是错误的。 getCurrentPosition
是HTML5功能。
除此之外,getCurrentPosition
需要一个回调。此外,在发送 ajax 请求之前,您不需要任何 php。
试试这个:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<div id="log"></div>
<form action="" method="post">
<input type="submit" name="ido" value="Click" /></td>
</form>
<script>
$(document).ready(function(){
$('form').submit(function(e){
e.preventDefault();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ajaxCall);
}else{
$('#log').html("GPS szolgáltatás nem müködik ezen a böngészőn, kérlek értesítsd a rendszergazdát!");
}
});
function ajaxCall(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url: "test.php",
type: 'POST', //I want a type as POST
data: {'latitude' : latitude, 'longitude' : longitude },
success: function(response) {
$('#log').html(response);
}
});
}
});
</script>
</body>
</html>
您的测试.php应如下所示:
<?php
echo 'Latitude: '.$_POST['latitude'].'<br>';
echo 'Latitude: '.$_POST['longitude'];
?>