如何使用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));
?>
最佳答案
改变
data: 'x='+coords.lon, 'y='coords.lat, 'number'=number
至
data: 'x='+coords.lon+'&y='+coords.lat+'&number='+number;
顺便说一句,在您的 PHP 文件中,您引用的是 id
,但您没有发送名为该变量的变量。
关于jquery - 发送多个变量到服务器 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10496662/