[英]Passing a variable with ajax from JS to PHP
我正在嘗試將gps坐標從JavaScript傳遞到同一頁面上的php變量,但是在腳本運行后並嘗試在php中回顯,它什么都沒顯示(注意:未定義索引:lat)。
<!DOCTYPE html>
<html>
<body>
<p id="gps"></p>
<script>
var x=document.getElementById("gps");
var y=document.getElementById("gps");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x=position.coords.latitude;
y=position.coords.longitude;
$.ajax({
type: 'POST',
url: 'index.php',
data: { lat: x },
});
</script>
PHP代碼:
echo "<script> getLocation(); </script>";
$lat=$_POST['lat'];
echo $lat;
如何將變量從Javascript傳遞到php?
加載jQuery庫:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
將上述<script>
標記插入<head>
。
由於$.ajax
是jQuery函數,因此必須首先加載jQuery才能使用它。
您還需要關閉showPosition
函數,並使用complete
返回的數據:
function showPosition(position){
x=position.coords.latitude;
y=position.coords.longitude;
$.ajax({
type: 'POST',
url: 'index.php',
data: { lat: x },
complete: function(text){ return text; }
});
}
從AJAX響應中調用javascript函數不是一個不錯的選擇。 所以我會在$ .ajax的 完整值函數中調用getLocation()函數:
function showPosition(position){
x=position.coords.latitude;
y=position.coords.longitude;
$.ajax({
type: 'POST',
url: 'index.php',
data: { lat: x },
complete: function(text){getLocation();return text;}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.