[英]Inserting values from JavaScript directly into MySQL database
我正在使用此JS函數來獲取訪問者的地理位置並將其顯示在頁面上。 這很好。
function onGeoSuccess(location) {
console.log(location);
var strLocation = '<b>Latitude:</b> ' + location.coords.latitude + '<br />' +
'<b>Longitude:</b> ' + location.coords.longitude + '<br />' +
'<b>City:</b> ' + location.address.city + '<br />' +
'<b>Country:</b> ' + location.address.country + '<br />' +
'<b>Country Code:</b> ' + location.address.countryCode + '<br />' +
'<b>Region:</b> ' + location.address.region + '<br />' +
'<b>Accuracy:</b> ' + location.coords.accuracy + '<br />' +
'<br />'
document.getElementById('geofound').innerHTML = strLocation;
}
//The callback function executed when the location could not be fetched.
function onGeoError(error) {
console.log(error);
}
window.onload = function () {
//geolocator.locateByIP(onGeoSuccess, onGeoError, 2, 'map-canvas');
var html5Options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 };
geolocator.locate(onGeoSuccess, onGeoError, true, html5Options, 'geo-details');
};
現在,我想在每次調用時將此信息保存到MySQL數據庫中。 就像是:
var strLocation = '$addtodb = "mysql_query('INSERT INTO gpsdb (lat, lon, city, country, code, region, accuracy) values (location.coords.latitude, location.coords.longitude, ...))"'
但是我認為這不是正確的方法。 直接從JS將信息輸入數據庫的正確方法是什么? 我不需要像現在在JS中那樣回顯信息,我寧願在將其輸入數據庫后從數據庫中提取該信息。 JS僅用於插入數據庫。
您將需要使用ajax調用您的服務器端語言http://api.jquery.com/jquery.ajax/ ,然后將信息插入數據庫
例如
發布到數據庫
function insertIntoDatabase(location){
$.ajax({
url: 'serversideurl',
type : "POST",
data: location,
success: function(response) {
// after success from server show the location on screen?
document.getElementById('geofound').innerHTML = response.location;
}
});
}
然后,您可以在服務器內部解析對象,或者在將其作為數據發送之前由客戶端完成。 並運行mysql_query
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.