繁体   English   中英

jQuery ajax将变量发布到php

[英]Jquery ajax Post variables to php

我的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>

首先,我知道有未使用的代码。 但是İ将使用此块。 不给我任何答复。 它必须成功地工作。 但这并没有在我的php页面中给我lat和lon变量。 还有一种将变量发送到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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM