【发布时间】:2018-01-23 14:41:25
【问题描述】:
我是 Ajax 的新手,我知道当我想将数据传递给 PHP 文件时我需要使用 Ajax,但我不确定 Ajax 是否可以像我编写的代码那样使用。如果不能,任何人都可以帮助我吗?因为我想使用 html5 地理位置来获取用户位置。我之前尝试过geoplugin,但我得到的IP总是服务器IP而不是用户IP,我尝试在这里询问geoplugin但没有用。我已经尝试过这个 html5 地理位置来显示我的 lon 和 lat,它是正确的,但我想将变量传递给另一个 PHP 文件以计算从 MySQL 获取的数据的最近距离。
在 index.php 中
<script>
$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation);
} else {
$('#location').html('Geolocation is not supported by this browser.');
}
});
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
type:'POST',
url:'index1.php',
data:'latitude='+latitude+'&longitude='+longitude
}
});
}
</script>
在 index1.php 中
<?php
session_start();
$link=mysqli_connect("localhost","id2135226_ukwai1203","ukwai1203");
mysqli_select_db($link,"id2135226_demo");
$lat=$_POST['latitude'];
$lon=$_POST['longitude'];
$sql = "select branch_id,(6371 * 2 * ASIN(SQRT( POWER(SIN(($lat -
branch_lat)*pi()/180/2),2)+COS($lat*pi()/180
)*COS(branch_lat*pi()/180)*POWER(SIN(($lon-branch_lon)*pi()/180/2),2))))
as
distance From Branch ORDER BY distance ASC LIMIT 1";
$res=mysqli_query($link,$sql);
while($row=mysqli_fetch_array($res)){
$_SESSION['location']=$row['branch_id'];
?>
<script>
window.location="http://ukwai1203.000webhostapp.com/fyp/user/shop.php";
</script>
<?php
}
?>
【问题讨论】:
-
@JayBlanchard 没有错误,只是一个空白页,我把这个文件放在一个虚拟主机服务器上
-
@JayBlanchard 忘记添加库,但添加后仍然是空白页
-
@JayBlanchardi 将
-
为什么不应该是空白页?其中唯一的 HTML 是
<script>元素,您的 JS 只发出 Ajax 请求:它对响应不做任何事情,也不向页面写入任何内容。
标签: php ajax html geolocation