Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用AJAX将值从JavaScript传递到PHP_Javascript_Php_Jquery_Html_Ajax - Fatal编程技术网

使用AJAX将值从JavaScript传递到PHP

使用AJAX将值从JavaScript传递到PHP,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,我不知道为什么我的代码不起作用,我正在尝试使用AJAX将坐标从JavaScript发送到PHP,并且我能够将值从JavaScript拉到textbox,但值不会传递到PHP。非常感谢您的帮助 <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script> <

我不知道为什么我的代码不起作用,我正在尝试使用AJAX将坐标从JavaScript发送到PHP,并且我能够将值从JavaScript拉到textbox,但值不会传递到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>

函数getLocation(){
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(showPosition);
}
}
功能显示位置(位置){
document.getElementById(“getlat”).value=position.coords.latitude;
document.getElementById(“getlon”).value=position.coords.longitude;
}
$(文档).ready(函数(){
$.ajax({url:samepage3.php),键入:“POST”,异步:false,
数据:{getlat:$(“#getlat”).val(),getlon:$(“#getlon”).val()}
});
});
更新1:


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

首先,分离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" />
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $lat = $_POST["getlat"];
    $lon = $_POST["getlon"];
    echo json_encode(array('lat' => $lat, 'lon' => $lon));
    exit;
}
?>

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

File index.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>

函数getLocation(){
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(showPosition);
}
}
功能显示位置(位置){
document.getElementById(“getlat”).value=position.coords.latitude;
document.getElementById(“getlon”).value=position.coords.longitude;
}
函数fireAjax(){
$.ajax({url:“response.php”,键入:“POST”,async:false,
数据:{getlat:$(“#getlat”).val(),getlon:$(“#getlon”).val(),
成功:功能(响应){
$('#response').html(response);
}
});
}
发送
文件response.php

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

根本原因是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> 

函数getLocation(){
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(showPosition);
}
}
功能显示位置(位置){
document.getElementById(“getlat”).value=position.coords.latitude;
document.getElementById(“getlon”).value=position.coords.longitude;
$.ajax({url:samepage3.php),键入:“POST”,异步:false,
数据:{getlat:$(“#getlat”).val(),getlon:$(“#getlon”).val()}
});
}
$(文档).ready(函数(){
});

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

ajax的唯一目的是从服务器获取和发送数据,而无需重新加载页面

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

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

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


函数getLocation(){
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(showPosition);
}否则{
控制台。警告(“无法地理定位!”);
//这将是一个依靠IP进行地理定位的好地方(需要AJAX)
}
}
功能显示位置(位置){
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;
}
$(文档).ready(函数(){
getLocation();
});

Try
数据:{'getlat':$(“#getlat”).val(),'getlon':$(“#getlon”).val()
PHP将仅在页面加载时执行。没有区别,仍然以与相同的方式工作before@BernardoLima-是的,如何在PHP之前加载JS?您的PHP需要在单独的页面上。只需使用单独的PHP页面。这是一个坏主意。@PHPglue是的,我知道这也是我的建议。老实说,我只是这样做,因为我无法分离无论如何,为一个演示的php文件打分。呃,
setTimeout
是一种可怕的、笨拙的方法。把代码放在回调函数中。为什么要把所有内容放在同一个页面上?@prabowurti它现在是分开的。好吗?你不能在第一个请求中获取数据,但你会在第二个请求中获取数据,这是一个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);
           }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>