我正在使用这个 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
关于javascript - 将 JavaScript 中的值直接插入 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34119336/