簡體   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