将$ _GET变量放在ajax函数中

时间:2014-01-19 14:23:10

标签: javascript php jquery html ajax

美好的一天。我想使用ajax函数将数据传输到我的php页面,但我使用$ _GET变量进行验证。当我放

$.ajax({
          type: "POST",
          url: "coordsave.php?username=<?php echo($_GET['username']);?>",
          data: {x: pos_x, y: pos_y,}
        }).done(function( msg ) {
          alert( "Data Saved: " + msg );
        });
  }

这是将数据发送到

的php页面
$x_coord=$_POST["x"];
$y_coord=$_POST["y"];
$id=$_GET["username"];

//Setup our Query
$sql = "UPDATE $coords SET x2='$x_coord', y2='$y_coord' WHERE user_uname='$id'";

//Execute our Query
if (mysql_query($sql)) {
      echo "success $x_coord $y_coord ";
     }
    else {
    die("Error updating Coords :".mysql_error());   
}

感谢您的帮助。我真的需要它。 :)

1 个答案:

答案 0 :(得分:1)

的JavaScript

$.ajax({
          type: "POST",
          url: "coordsave.php?username=<?php echo(htmlspecialchars(isset($_GET['username']) ? $_GET['username'] : '', ENT_QUOTES, 'UTF-8'));?>",
          data: {x: pos_x, y: pos_y,}
        }).done(function( msg ) {
          alert( "Data Saved: " + msg );
        });
  }

PHP

header('Content-Type: text/plain; charset=utf-8');

$x = isset($_POST["x"]) or die('Param x required with POST');
$y = isset($_POST["y"]) or die('Param y required with POST');
$id = isset($_GET["username"]) or die('Param username required with GET');

//Setup our Query
$sql = sprintf(
    "UPDATE table_name SET x2='%s', y2='%s' WHERE user_uname='%s'",
    mysql_real_escape_string($x),
    mysql_real_escape_string($y),
    mysql_real_escape_string($id)
);

//Execute our Query
if (mysql_query($sql)) {
    echo "success $x $y";
} else {
    die("Error updating Coords :" . mysql_error());   
}

但是,所有mysql_*功能都已正式已弃用,因此您应使用PDOMysqli