使用AJAX发送lat& lng变量到PHP进行邻近计算 [英] Using AJAX to send lat & lng variables to PHP for proximity calculation

查看:85
本文介绍了使用AJAX发送lat& lng变量到PHP进行邻近计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个MySQL数据库(真正的单个表),有9个条目用于测试。我的目标是加载一个启用位置感知的主页面,使用Javascript将用户的纬度和经度设置为变量,然后使用AJAX,将这些内容发送给用户变量到另一个.php页面,这样变量可以放入我的查询中的计算公式中。还有第二个AJAX实例,它在变量发送完毕并处理整个页面后从服务器获取查询结果。



我的第二个AJAX实例非常成功从第二页调用结果。如果我手动设置变量,我会得到我很好的排序列表,如果我依赖于Javascript变量,则会产生错误。我不知道自己出错的地方。



我知道这可能看起来像一个重复的问题。我花了最后8小时阅读其他我希望能帮助我的问题。不幸的是,我尝试过的每个示例都不起作用。



我的主页(test.php)上的代码是这样的:

 < html>< head>< / head>< body> 
< script type =text / javascript>
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(函数(位置)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
$ .ajax({
type:POST,
url:locations-ajax.php,
data:' x ='+ lat +'& y ='+ lng,
});
});
}
< / script>
<! - 开始列表区域 - >
< script>
函数getXMLHttp()
{
var xmlHttp
尝试
{
// Firefox,Opera 8.0+,Safari
xmlHttp = new XMLHttpRequest ();

catch(e)
{
// Internet Explorer
尝试
{
xmlHttp = new ActiveXObject(Msxml2.XMLHTTP );

catch(e)
{
try
{
xmlHttp = new ActiveXObject(Microsoft.XMLHTTP);
}
catch(e)
{
alert(您的浏览器不支持AJAX!)
return false;
}
}
}
return xmlHttp;

函数MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);


xmlHttp.open(GET,locations-test.php,true);
xmlHttp.send(null);
}

函数HandleResponse(响应)
{
document.getElementById('listarea')。innerHTML = response;
}
< / script>
< div class =container>< input type ='button'onclick ='MakeRequest();'value ='Get List'/>< / div>
< div class =container>< div id =listarea>
< / div>< / div>< / div>
< / body>
< / html>

我的页面生成我的排序列表:(locations-test.php)

 <?php 
/ * $ x = 32.839001;
$ y = -79.852316; * /
mysql_connect(localhost,root,)或die(mysql_error());
echo连接到MySQL< br />;
mysql_select_db(test_db)或死(mysql_error());
回显连接到数据库< br>;
//建立一个MySQL连接
$ x = @ $ _ POST ['x'];
$ y = @ $ _ POST ['y'];
if(!empty($ x)){
echo'x not empty';
} else {
echo'x未设置或为空';
}
echo$ x;
回显< br>;
if(!empty($ y)){
echo'y not empty';
} else {
echo'y未设置或为空';
}
回显< br>;

$ query =SELECT *,(3959 * acos(cos(弧度($ x))* cos(弧度(lat))* cos(弧度(lng) - 弧度($ y)) + sin(弧度($ x))* sin(弧度(lat))))AS距距离距离<2500 ORDER BY distance LIMIT 0,20;;
$ result = mysql_query($ query)或die(mysql_error());
while($ row = mysql_fetch_array($ result)){
echo< div class ='row'>< div class ='logo'>< img src ='foo。 png'width = '20'height ='20'>< / div>< div class ='siteblock'>< div class ='sitename'>;
echo $ row ['site_name'];
echo< / div>< div class ='address'>;
echo $ row ['street_number'];
echo;
echo $ row ['street_name'];
echo< / div>< / div>< / div>;
}
?>

我在代码中留下了测试,但注释掉了。如果我给变量赋值,我在表格中得到正确的结果,并且它很好地输出到test.php。



页面连接到数据库就好了,但lat和lng的值不会从test.php传递到locations-test.php。

我真的不确定我错过了什么,但希望它是简单的事情。我使用PHP 5.4.3,MySQL 5.5.24和Apache 2.2.22运行WAMP 64位。



我宁愿希望它是我的一部分而不是其他任何东西。

div>

由于您使用的是jQuery,所以绝对不需要使用XMLHTTP函数。此外,它似乎是你试图通过jQuery发送数据,并通过XMLHTTP检索;这是不正确的。您可以像这样重写代码:

  if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function (位置){
$ .ajax({
类型:POST,
url:locations-ajax.php,
data:{
x:position .coords.latitude,
y:position.coords.longitude
},
成功:函数(data){
$(#listarea)。html(data);
}
});
});
}


To start, thank you in advance for all insight and assistance.

I have a MySQL database (single table, really) with 9 entries for testing. Fields include id, name, address, city, state, zip, lat, lng, etc. My goal is to load a main page with location awareness enabled, use Javascript to set user latitude and longitude as variables, then using AJAX, send those variables to another .php page so the variables can be placed into the calculation formula in my query. There is a second AJAX instance which then fetches the results of the query from the server after the variables have been sent and the whole page processed.

My second AJAX instance very successfully calls the results from the second page. If I manually set the variables, I get my nicely sorted list, and if I rely on the Javascript variables, I am fed an error. I'm not sure where I am going wrong.

I am aware this may seem like a duplicate question. I've spent the last 8 hours on SO reading other questions which I had hoped would help me. Unfortunately, every example I have tried does not work.

My code on my main page (test.php) is this:

<html><head></head><body>
<script type="text/javascript">
if(navigator.geolocation)
  {
  navigator.geolocation.getCurrentPosition(function(position)
   {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
$.ajax({
        type: "POST", 
        url:  "locations-ajax.php", 
        data: 'x='+lat+'&y='+lng,
        });  
 });
}
</script>
<!--begin list area-->
<script>
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
  try
  {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch(e)
  {
    alert("Your browser does not support AJAX!")
    return false;
  }
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
  HandleResponse(xmlHttp.responseText);
}
  }
 xmlHttp.open("GET", "locations-test.php", true); 
 xmlHttp.send(null);
}

function HandleResponse(response)
{
document.getElementById('listarea').innerHTML = response;
}
</script>
<div class="container"><input type='button' onclick='MakeRequest();' value='Get List'/></div>
<div class="container"><div id="listarea">
</div></div></div>
</body>
</html>

My page to generate my sorted list is this: (locations-test.php)

<?php
/*   $x = 32.839001;
$y = -79.852316;   */
mysql_connect("localhost", "root", "") or die(mysql_error());
 echo "Connected to MySQL<br />";
mysql_select_db("test_db") or die(mysql_error());
 echo "Connected to Database <br>";
// Make a MySQL Connection
  $x = @$_POST['x'];
  $y = @$_POST['y']; 
 if (!empty($x)){
        echo 'x not empty';
    }else{
        echo 'x is not set or empty';
    }
    echo "$x";
 echo "<br>";
    if (!empty($y)){
        echo 'y not empty';
    }else{
        echo 'y is not set or empty';
    }
 echo "<br>";  

$query = "SELECT * , ( 3959 * acos( cos( radians($x) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($y) ) + sin( radians($x) ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < 2500 ORDER BY distance LIMIT 0 , 20;"; 
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
    echo "<div class='row'><div class='logo'><img src='foo.png' width='20' height='20'></div><div class='siteblock'><div class='sitename'>"; 
    echo $row['site_name'];
    echo "</div><div class='address'>"; 
    echo $row['street_number'];
    echo " ";  
    echo $row['street_name'];
    echo "</div></div></div>"; 
}
?>

I've left my tests in the code, but commented out. If I assign the variables a value, I get the proper results in my table, and it outputs nicely to test.php.

The page connects to the database just fine, but the values for lat and lng do not pass from test.php to locations-test.php.

I'm really not sure what I am missing, but hopefully it is something simple. I am running WAMP 64 bit with PHP 5.4.3, MySQL 5.5.24, and Apache 2.2.22.

I would rather hope it is oversight on my part rather than anything else.

解决方案

Since you're using jQuery there is absolutely no need to use the XMLHTTP functions. Also, it seems like you're trying to send data via jQuery and retrieve via XMLHTTP; that is incorrect. You could rewrite your code like this:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
        $.ajax({
            type: "POST",
            url: "locations-ajax.php",
            data: {
                x: position.coords.latitude,
                y: position.coords.longitude
            },
            success: function (data) {
                $("#listarea").html(data);
            }
        });
    });
}

这篇关于使用AJAX发送lat&amp; lng变量到PHP进行邻近计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆