2016-04-03 99 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>