无法看到ajax调用的结果

时间:2013-10-26 11:07:12

标签: javascript php jquery ajax

我试图将ajax respone存储到Post php变量,然后在同一页面上回显它,但遗憾的是,它返回“Notice:Undefined index”

我认为这与ajax的成功部分有关。你可以帮我纠正吗?

提前致谢:)

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
    <form action="" method="post">
    <input type="submit" name="ido" value="Click" /></td>
    </form>
    <script>

var x=document.getElementById("log");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="GPS szolgáltatás nem müködik ezen a böngészőn, kérlek értesítsd a rendszergazdát!";}
  }
function showPosition(position)
  {
    navigator.geolocation.getCurrentPosition(showPosition);
     var latitude = position.coords.latitude;
     var longitude = position.coords.longitude;
     $.ajax({
         url: "test.php", 
         type: 'POST', //I want a type as POST
         data: {'name' : latitude },
         success: function(response) {
        alert(response);
      }
      });
    }
</script>

<?php 
    if(isset($_POST["ido"])){
    echo "<script>getLocation();</script>";
    $name=$_POST["name"];
print_r($_POST);
    }
?>
</html>

1 个答案:

答案 0 :(得分:0)

首先,您的DOCTYPE声明是错误的。 getCurrentPositionHTML5 feature

此外getCurrentPosition需要回调。 此外,在发送ajax请求之前,您不需要任何php。

试试这个:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <meta charset="utf-8">
        <title>Title</title>
    </head>
    <body>

    <div id="log"></div>

    <form action="" method="post">
        <input type="submit" name="ido" value="Click" /></td>
    </form>

    <script>
    $(document).ready(function(){
        $('form').submit(function(e){
            e.preventDefault();         

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(ajaxCall);         
            }else{
                $('#log').html("GPS szolgáltatás nem müködik ezen a böngészőn, kérlek értesítsd a rendszergazdát!");
            }

        });

        function ajaxCall(position){
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;

            $.ajax({
                url: "test.php", 
                type: 'POST', //I want a type as POST
                data: {'latitude' : latitude, 'longitude' : longitude },
                success: function(response) {
                    $('#log').html(response);
                }
            });
        }       
    });
    </script>
    </body>
</html>

您的test.php应如下所示:

<?php
    echo 'Latitude: '.$_POST['latitude'].'<br>';
    echo 'Latitude: '.$_POST['longitude'];
?>