如何使用jQuery.ajax
. 我需要将变量中的值发送到更新 mySQL 的外部 PHP 文件。这是我现在使用的代码:
Javascript:
var number= localStorage.getItem("number")
var coords = {lat: "", lon: ""};
window.onload = function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
coords.lat = position.coords.latitude;
coords.lon = position.coords.longitude;
x.innerHTML="Latitude: " + coords.lat + "<br />Longitude: " + coords.lon;
}
function sendToServer() {
// here you can reuse the object to send to a server
alert(coords.lon);
}
function Updatelocation() {
jQuery.ajax({
type: "POST",
url: "location.php",
data: 'x='+coords.lon, 'y='coords.lat, 'number'=number
cache: false,
success: function(response) {
alert("Record successfully updated");
}
});
}
和location.php
:
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$x = @$_POST['x'];
$y = @$_POST['y'];
$num = @$_POST['num'];
// query
$sql = "update table set
x=? ,
y=?
where num='?'";
$q = $conn->prepare($sql);
$q->execute(array($x, $y, $num));
?>