【发布时间】:2012-12-12 08:53:43
【问题描述】:
我有一个脚本,我试图将一些位置信息发送到一个 php 页面,执行一个 mysql 搜索查询并在不转到另一个页面的情况下获取结果。
我的 php 工作正常,并且我的页面工作正常,它重定向到 php 页面,但是当我尝试使用下面的代码时,我没有得到任何传回的结果。
Javascript 代码
function phpRedirect(loc) {
// var radius = get('r'); // Retrieve GET values for search radius and
// var numResults = get('n'); // number of results
var radius = 10; // Retrieve GET values for search radius and
var numResults = 5; // number of results
var latitude = loc.coords.latitude; // Get long, lat and accuracy from
var longitude = loc.coords.longitude; // location object
var accuracy = loc.coords.accuracy;
var xmlHttp = new XMLHttpRequest(); //not the cross browser way of doing it
xmlHttp.open("GET", "find.php?lat=" + latitude + "&long=" +
longitude + "&acc=" + accuracy + "&r=" + radius
+ "&n=" + numResults, true);
xmlHttp.send(null);
}
$(function ()
{
$.ajax({
url: 'find.php', //the script to call to get data
type: "post",
data: { getData: true },
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var name = data[0];
$('#output').html("<b>username: </b>"+username);
}
});
});
function error(loc) {
// This is called if the location can't be found.
document.write("Error finding GPS location");
}
// Use navigator to get current user location. If found, calls 'phpRedirect()',
// If not available calls 'error()'. Includes timeout and ensures highest acc.
navigator.geolocation.getCurrentPosition(phpRedirect, error, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
<div id="output">this element will be accessed by jquery and this text replaced </div>
下面是我的 php 查询的输出,
$result=mysql_query($query) or die (mysql_error());
while($row=mysql_fetch_assoc($result)) $data[]=$row; // Turn result to array
$acc_package = array('location_accuracy'=>"$accuracy"); // Include result array
$output[] = $acc_package; // and accuracy value inside
$output[] = $data; // an output array.
print(json_encode($output)); // Convert output array to json format and print
结果如下
[{"location_accuracy":"122000"},[{"username":"bobbyj","distance":"0.484367160806139"}]]
【问题讨论】:
-
注意! PHP 的未来版本将弃用和删除
mysql_系列函数。现在是switch to PDO 或mysqli 的好时机。 -
另外,为什么以所有美好和神圣的名义,您将现代 jQuery 与史前手动 ajax 结合起来?
-
@Charles 哈哈,那里甚至还有一个
$.ajax电话! -
您的 .ajax 调用不会向服务器发送任何数据。其实为什么会在那里?
-
同意@Charles 的观点,决定一种执行ajax 调用的方法。但是对于这个问题,我看不到您在成功函数中定义变量用户名的位置。你有没有尝试过类似 console.dir(data);在成功函数中?验证您从请求中获取的数据和正确的格式
标签: php javascript ajax