这是我第一次使用AJAX,我正在尝试将JS变量发送到PHP脚本。我有一个XMLHttpRequest,但似乎并不完整 - 我缺少什么?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else {
document.write("Geolocation is required for this page.");
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// document.write("<a href='http://api.geonames.org/findNearbyPlaceNameJSON?lat="+lat+"&lng="+lng+"&username=sebastiano'>my town</a>");
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","location.php?lat=position.coords.latitude",true);
xmlhttp.send();
// SOMETHING MISSING HERE?
}
function errorFunction(position) {
document.write("Error");
}
答案 0 :(得分:3)
您似乎没有将变量的内容传递给open命令。
xmlhttp.open("GET","location.php?lat=position.coords.latitude",true);
在此示例中,您的lat将包含一个内容为“position.coords.latitude”的字符串
而不是尝试
xmlhttp.open("GET","location.php?lat="+position.coords.latitude,true);
或者更好的是,使用您在函数顶部创建的变量并传递long和lat。
xmlhttp.open("GET","location.php?lat=" + lat + "&long=" + lng,true);
答案 1 :(得分:2)
你发送的是“position.coords.latitude”作为价值......
尝试xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
另外,看看jQuery
答案 2 :(得分:1)
试试这个:
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
xmlhttp.send();