【问题标题】:How to get information in jquery function from the php file如何从 php 文件中获取 jquery 函数中的信息
【发布时间】:2015-06-28 18:28:45
【问题描述】:

我的问题是如何从 php 文件到 jquery ajax 脚本获取 db 信息(在我的情况下只是一个数字)所以这是我的 jquery:

function rate_down(id) { 
    var id = id;
//submit data to php script

    var data = {
      "id": id,
    };

    $.ajax({
      type: "POST",
      url: "rating.php",
      data: data,
      success: function(response) {

      var currentValue = /* here i want to put the db number */
      var newValue = +currentValue - 1;
      $("#points_"+id).text(newValue);




      },
      error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
      } 
    });
};

我想要我的 raiting.php。我不确定是否应该发布它,因为它没用,但这是我在 raiting.php 中的 mysql 查询:

$pic_id = (int) $_REQUEST['id'];
mysql_query = mysql_query"SELECT points FROM `photos` WHERE `id` = '$pic_id'";

【问题讨论】:

  • 安全提示:使用这样的 MySQL 查询容易发生 SQL 注入。非常不鼓励在系统的生产环境中使用 ;)

标签: php jquery mysql ajax json


【解决方案1】:

问题出在您的 php 脚本中。请不要使用mysql_query。使用PDO

$pic_id = (int) $_REQUEST['id'];

$db = new PDO("...");
$q = $db->prepare("SELECT points FROM `photos` WHERE `id` = :pic_id");
$q->bindValue(':pic_id', $pic_id);
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $points = $check['points'];
}else{
    $points = 0;
}

echo $points;

然后在你的 ajax 函数中:

$.ajax({
    type: "POST",
    url: "rating.php",
    data: data,
    success: function(response) {

        if(response != 0) {
            var currentValue = response;
            var newValue = +currentValue - 1;
            $("#points_"+id).text(newValue);
        }

    },
    error: function(jqXHR, textStatus, errorThrown){
    alert(errorThrown);
    } 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    • 2012-01-11
    • 2021-12-04
    相关资源
    最近更新 更多