2016-04-03 98 views
0

我ajax.php腳本jQuery的ajax的POST變量到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> 

首先,我知道有未使用的代碼。但是我會用這個塊。 İt不給我任何迴應。我必須成功地工作。 但它不會給我在我的PHP頁面經緯度變數。 İf有另一種方式發送變量到PHP頁面,我可以嘗試。

+1

你的Ajax調用從未,因爲你有語法錯誤。你有一個額外的關閉'}',並且'data:{lat:lat,lon:lon}'後面缺少逗號,如果你打開了瀏覽器控制檯,你會注意到它。 – adeneo

+0

@adeneo非常感謝你。非常感謝。 İt現在工作。再次感謝你。我從1周開始處理。 –

回答

0

代碼中沒有功能問題。但是有一些語法錯誤會阻止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>