【问题标题】:Passing values from JavaScript to PHP using AJAX使用 AJAX 将值从 JavaScript 传递到 PHP
【发布时间】:2014-10-21 17:59:54
【问题描述】:

我不知道为什么我的代码不起作用,我正在尝试使用 AJAX 将坐标从 JavaScript 发送到 PHP,并且我能够将值从 JavaScript 提取到文本框,但值不会传递给 PHP。非常感谢任何帮助。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    document.getElementById("getlat").value = position.coords.latitude;
    document.getElementById("getlon").value = position.coords.longitude;
}
$( document ).ready(function() {
$.ajax({url:"samepage3.php",type:"POST",async:false,
   data:{getlat:$("#getlat").val(),getlon:$("#getlon").val()}
});
});
</script>
</head>
<body onload="getLocation()">
<input type="text" id="getlat" name="getlat" /> 
<input type="text" id="getlon" name="getlon" />
<?php
if(isset($_POST["getlat"]))
{
    $lat = $_POST["getlat"];
    echo $lat;
}
if(isset($_POST["getlon"]))
{
    $lon = $_POST["getlon"];
    echo $lon;
}
?>
</body>
</html>

更新 1:

我在文件 samepage3.php 中运行此代码,我需要在同一页面上执行操作而不重新加载页面

【问题讨论】:

  • 试试data:{'getlat':$("#getlat").val(),'getlon':$("#getlon").val()
  • PHP 只会在页面加载时执行。
  • 没区别,还是和以前一样工作
  • @BernardoLima - 是的,我怎样才能让 JS 在 PHP 之前加载?
  • 你的 PHP 需要在一个单独的页面上。

标签: javascript php jquery html ajax


【解决方案1】:

首先,分离 PHP 处理。现在,在使用回调获取位置后,然后执行 AJAX。示例代码:

samepage3.php

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}

function showPosition(position) {

    $("#getlat").val(position.coords.latitude);
    $("#getlon").val(position.coords.longitude);
    $.ajax({
        url: 'request.php',
        type: 'POST',
        dataType: 'JSON',
        data:{
            getlat: $("#getlat").val(),
            getlon: $("#getlon").val()
        },
        success: function(response) {
            console.log(response);
        }
    });
}

$(document).ready(function() {
    getLocation();
});
</script>
<body>
<input type="text" id="getlat" name="getlat" />
<input type="text" id="getlon" name="getlon" />

request.php

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $lat = $_POST["getlat"];
    $lon = $_POST["getlon"];
    echo json_encode(array('lat' => $lat, 'lon' => $lon));
    exit;
}
?>

【讨论】:

  • 只使用一个单独的 PHP 页面。这是个坏主意。
  • @PHPglue 是的,老实说,我知道这就是我的建议,我只是这样做,因为无论如何我都无法为演示分离 php 文件。
  • 呃,setTimeout 是一种可怕的、笨拙的方式。将该代码放入回调函数中。
  • 为什么要把所有东西都放在同一个页面上?
  • @PrabowoMurti 现在分开了。好吗?
【解决方案2】:

你不能在samepage3.php上执行PHP脚本,页面完全加载之后。我建议分离页面,并使用 AJAX 创建响应。像这样的。

文件索引.php

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
        <script>
            function getLocation() {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(showPosition);
                }

            }
            function showPosition(position) {
                document.getElementById("getlat").value = position.coords.latitude;
                document.getElementById("getlon").value = position.coords.longitude;
            }

            function fireAjax(){
                $.ajax({url:"response.php",type:"POST",async:false,
                    data:{getlat:$("#getlat").val(),getlon:$("#getlon").val()},
                    success: function (response){
                        $('#response').html(response);
                    }
                });
            }
        </script>
    </head>
    <body onload="getLocation()">
        <input type="text" id="getlat" name="getlat" /> 
        <input type="text" id="getlon" name="getlon" />

        <button onclick="fireAjax()" >Send</button>

        <div id="response">
        </div>
    </body>
</html>

文件 response.php

<?php
if (isset($_POST["getlat"]))
{
    $lat = $_POST["getlat"];
    echo 'Latitude: ', $lat, '<br/>';
}
if (isset($_POST["getlon"]))
{
    $lon = $_POST["getlon"];
    echo 'Longitude : ', $lon;
}

【讨论】:

    【解决方案3】:

    根本原因是getLocation函数会有很大的延迟,所以你需要在getLocation完成后触发ajax调用。请看一击修改版:

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script>
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
    }
    function showPosition(position) {
        document.getElementById("getlat").value = position.coords.latitude;
        document.getElementById("getlon").value = position.coords.longitude;
        $.ajax({url:"samepage3.php",type:"POST",async:false,
               data:{getlat:$("#getlat").val(),getlon:$("#getlon").val()}
            });
    }
    $( document ).ready(function() {
    
    });
    </script>
    </head>
    <body onload="getLocation()">
    <input type="text" id="getlat" name="getlat" /> 
    <input type="text" id="getlon" name="getlon" />
    <?php
    if(isset($_POST["getlat"]))
    {
        $lat = $_POST["getlat"];
        echo $lat;
    }
    if(isset($_POST["getlon"]))
    {
        $lon = $_POST["getlon"];
        echo $lon;
    }
    ?>
    </body>
    </html> 
    

    唯一的变化是在函数 showPosition 中进行 ajax 调用。

    【讨论】:

    • 第一个请求中无法获取数据,但您将在第二个请求中获取数据,这是一个ajax调用。
    【解决方案4】:

    AJAX 的唯一目的是在不重新加载页面的情况下从服务器获取和发送数据。

    您不需要来自服务器的任何数据。您需要来自浏览器的数据——即——地理位置坐标,因此 AJAX 和 php 与您需要在此处执行的操作无关。这可以在纯 HTML 中完成。

    另一方面,如果您想在导航器不支持地理定位时将坐标保存到数据库或使用 IP 地址作为后备,那么您可以使用服务器的帮助,而 AJAX 会发挥作用。

    只需将您的 ajax 函数替换为 getLocation()

    <!DOCTYPE html>
      <html>
        <head>
          <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
          <script>
            function getLocation() {
              if (navigator.geolocation) {
                     navigator.geolocation.getCurrentPosition(showPosition);
               }else{
                 console.warn("Can't geolocate!");
                 //this would be a good place to fall back on geolocation by IP (AJAX necessary)
               }
            }
    
            function showPosition(position) {
              console.info('Latitude: ' + position.coords.latitude);
              document.getElementById("getlat").value = position.coords.latitude;
              console.info('Longitude: ' + position.coords.longitude);
              document.getElementById("getlon").value = position.coords.longitude;
            }
            $( document ).ready(function() {
                getLocation();
            });
          </script>
       </head>
       <body>
         <input type="text" id="getlat" name="getlat" /> 
         <input type="text" id="getlon" name="getlon" />
       </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      相关资源
      最近更新 更多