如何使用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));
?>
答案 0 :(得分:4)
更改
data: 'x='+coords.lon, 'y='coords.lat, 'number'=number
到
data: 'x='+coords.lon+'&y='+coords.lat+'&number='+number;
顺便说一句,在你的PHP文件中,你引用的是id
,但你没有发送一个名为的变量。
答案 1 :(得分:1)
我使用JSON:
data = {
x: cords.lon,
y: cords.lat,
number:number
}
jQuery.ajax({
type: "POST",
url: "location.php",
data: 'data='+JSON.stringify(data),
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);
// data from javascript
$data = json_decode($_POST['data']);
// query
$sql = "update table set
x=? ,
y=?
where num='?'";
$q = $conn->prepare($sql);
$q->execute(array($data->{'x'}, $data->{'y'}, $data->{'number'}));
?>
答案 2 :(得分:0)
为了便于阅读,我使用了一个结构:
jQuery.ajax({
type: "POST",
url: "location.php",
data: {
x : coords.lon,
y : coords.lat,
num : number
},
cache: false,
success: function(response) {
alert("Record successfully updated");
}
});
另外:在你的php中你使用“num”而不是“number”
编辑:并删除上一个问号周围的引号
$sql = "update table set
x=? ,
y=?
where num=?";
而不是
$sql = "update table set
x=? ,
y=?
where num='?'";