【问题标题】:Jquery ajax Post variables to phpJquery ajax 将变量发布到 php
【发布时间】:2016-07-23 05:34:52
【问题描述】:

我的 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 调用永远不会进行,因为您有语法错误。您有一个额外的结束 },并且您在 data: { lat:lat, lon:lon} 之后缺少逗号,如果您打开浏览器控制台,您会注意到这一点。
  • @adeneo 非常感谢。我非常感谢。它现在正在工作。再次感谢你。自 1 周以来,我处理了它。

标签: javascript php jquery ajax w3c-geolocation


【解决方案1】:

代码中没有功能问题。但是有一些语法错误会阻止 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多