将JavaScript中的值直接插入MySQL数据库

时间:2015-12-06 15:48:58

标签: javascript mysql insert geolocation

我正在使用此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只能用于插入DB。

1 个答案:

答案 0 :(得分:0)

您需要对服务器端语言使用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