[英]Posting Geolocation data to PHP using AJAX
我已經瀏覽了一些類似的主題-但無法確切看到我要去哪里。 我使用AJAX和PHP在正在創建的應用程序上保存用戶的經度。 我知道AJAX和PHP可以正常工作,因為它將所有內容(甚至是虛擬的lat和lng值)保存到我的數據庫表中。 我已經使用變量兩個小時了,到目前為止,我獲得的最好結果是在數據庫中插入了“ 0”值。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
getCurrentLocation();
}
function onError(message) {
navigator.notification.alert(message, "", "Error");
}
function getCurrentLocation() {
navigator.geolocation.getCurrentPosition(locationSuccess, onError);
}
function locationSuccess(position) {
lat = document.getElementById("latSpan");
lon = document.getElementById("latSpan");
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
//recording function
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
xmlhttp.open("POST","http://www.lauracrane.co.uk/app/rec/location.php",true); //
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("latitude=" + latitude + "&longitude=" + longitude);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}}'
我想知道是否有人可以看到為什么不將lat&lng的值傳遞給AJAX函數。
任何幫助,將不勝感激。 :)
勞拉
也許我們看不到所有代碼,但是看起來緯度和經度的功能范圍僅限於locationSuccess。 因此,當您嘗試在ajaxFunction中訪問它們時,它們將獲得默認值。
而且,您不需要做所有有趣的getXMLObject。 在Android,iOS和BlackBerry等Webkit瀏覽器中,您只需要執行以下操作:
var xmlhttp = new XMLHttpRequest();
最后,由於您可能是在file://協議之外運行的,因此您必須查找狀態碼0,在這種情況下,該狀態碼類似於200。
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200 || xmlhttp.status == 0) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
}
// etc.
}
為什么不只使用jQuery ajax調用呢? 您的代碼已針對IE6進行了標記...由於在phonegap中已對此進行了標記,因此我認為您可以使用更新的方法進行訪問。
我建議使用jQuery ajax。
function ajaxFunction() {
$.ajax({
url:'http://www.lauracrane.co.uk/app/rec/location.php',
type:'POST',
data:'lat='+lat+'&long='+long,
success:function(d){
console.log(d);
},
error(w,t,f){
console.log(w+' '+t+' '+f);
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.