1

我正在尝试制作一个用于发送谷歌地图坐标以填充 mysql 数据库的测试页面。我正在使用 ajax 将数据发送到 php。Firebug 显示数据正在发送。但是这个php错误出来了。并且 mysql 数据库在没有地图坐标的情况下填充。

这是 Ajax 函数:

function sendData(geodata){
    var hr = new XMLHttpRequest();
    hr.open("POST","getdata.php",true);
    hr.setRequestHeader("Content-type","application/json");

    if(hr.readyState==4 && hr.status==200){
            var data =  JSON.parse(hr.responseText);
            alert("Data received about "+data);
            }//end if

    hr.send("geodata="+geodata);
}//close sendData

这是 PHP 页面。

    <?php
header("Content-Type : application/json");

$loc = $_POST["geodata"];

$username="root";
$password="";
$database="location";

$connection = mysql_connect('localhost',$username,$password);
if(!$connection){
    die('Unable to connect to the server '.mysql_error());
    }

$selectdb = mysql_select_db($database);
if(!$selectdb){
    die('Unable to connect to database'.mysql_error());
    }

$query = "INSERT INTO `location_data`(`ltlng`) VALUES ('".$loc."')";
$result = mysql_query($query);
if(!$result){
    die('Invalid query : '.mysql_error());
    }
?>

然后出现以下错误。

( ! ) Notice: Undefined index: geodata in C:\wamp\www\IndustryProject\SampleDataGen\getdata.php on line 4

任何帮助将不胜感激。谢谢。

4

1 回答 1

2

当您将数据作为查询字符串发布时,请尝试使用application/x-www-form-urlencoded内容类型,而不是application/json您当前的类型:

hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
于 2012-10-23T12:37:27.620 回答