2

如何使用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));
?>
4

3 回答 3

4

改变

data: 'x='+coords.lon, 'y='coords.lat, 'number'=number

data: 'x='+coords.lon+'&y='+coords.lat+'&number='+number;

顺便说一句,在您的 PHP 文件中,您引用的是id,但您没有发送一个名为 that 的变量。

于 2012-05-08T10:18:15.933 回答
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");
    }
});

位置.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'}));
?>
于 2012-05-08T10:25:48.057 回答
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='?'";
于 2012-05-08T10:24:30.007 回答