【问题标题】:How to perform ajax post request to get some values from the last row of?如何执行ajax post请求以从最后一行获取一些值?
【发布时间】:2017-08-22 11:34:36
【问题描述】:

您好,我被要求使用ajax post 请求从数据库的最后一行获取一些数据。 我有两个文件,它们是 PHP 脚本,用于连接到数据库并获取所有数据并将数据转换为json 格式。我对 PHP 脚本执行了 ajax 发布以获取所有数据。我想修改 ajax 帖子以从数据库中表的最后一行请求额外的数据。

例如student表中,数据库中有10行数据。我想从最后一行获取数据。我的问题是如何从数据库中的最后一行获取值.. 要求:不要修改SQL 代码,因为我需要所有数据以及最后一行数据。 我不要这个代码 data[9]['student_name'];

下面是我的代码... html文件

<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script> 
</head>
<div id="result"</div>
<script type="text/javascript">
showData();
function showData()
{
    $.ajax({
        type: "post",
        url: "student.php",
        dataType: "json",
        data: "how to request data from the last row of the database????
        success: function(data){
            console.log(data);
        }
    });
};

</script>
</body>
</html>

php 脚本

<?php

$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');

$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
    $json_array[] = $row;
}

echo json_encode($json_array);
?>

我的问题是如何从数据库的最后一行获取数据?

要求:不要修改SQL代码,我只想修改ajax post。请帮我。这是我的项目。

【问题讨论】:

  • 如果您既不更改请求也不更改查询 - 这将保留所有数据 - 您必须获取 javascript 中的最后一行,例如data[data.length - 1].
  • @DontVoteMeDown 嗨,我不明白你在说什么……我应该在哪里实现该代码????
  • 这是我应该实现该代码的地方吗??? $.ajax({ type: "post", url: "student.php", dataType: "json", data: data[data.length-1]

标签: php jquery sql json ajax


【解决方案1】:

如下更改PHP代码。

<?php

$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');

$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
    $json_array[] = $row;
}
$limit = count($json_array);
echo json_encode($json_array[$limit-1]);
?>

【讨论】:

    【解决方案2】:

    你的问题有点不清楚。似乎您想在最后一行向 PHP 发送一个参数,但我不确定。如果这是真的,您可以按照@Rossi 建议的方式添加一个参数,例如:

    data: {
        lastOnly: true
    }
    

    在脚本的最后:

    if (!isset($_POST["lastOnly"])) {
        echo json_encode($json_array);
    } else {
        echo json_encode($json_array[count($json_array)-1]);
    }
    

    但是,如果仍然想从后端获取所有数据但处理 javascript 中的最后一行,您可以按照我在 cmets 中所说的操作:

    success: function(data) {
        var lastRow = data[data.length - 1];
    }
    

    更新:只获取一个字段。

    1. 您只能发回一个值,您的 data 将收到一个字符串而不是一个 json 对象:

      echo $json_array["student_name"];
      
    2. 您可以从您的 json 对象中获取该属性:

      data.student_name
      

    【讨论】:

    • HI 那是我正在寻找的代码......但是我应该如何从最后一行中只获取学生姓名,因为我不想要其他数据,例如学生宗教学生性别和学生年龄
    猜你喜欢
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多