【问题标题】:How to fetch data row by row from mysql table, queries coded in php, using jquery (AJAX)?如何从 mysql 表中逐行获取数据,使用 php 编码的查询,使用 jquery(AJAX)?
【发布时间】:2015-08-30 11:32:09
【问题描述】:

我是 Ajax 的初学者。我想从主题表中获取数据行,它只包含一列主题为 varchar(100),在 MySQL DB 中定义。以下是我的php代码。

数据.php

<?php

$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: " .mysqli_connect_error());

$sql="select * from Subject";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
 {
    echo $row["SUBJECT"];
    //I Want This Value to Be received in my Jquery Page
    //So that i can take certain action based on each Subject.
    //For example creating a select box child elements,options.
 }
?>

Jquery.js

$(document).ready(function()
 {
    var response='';
    $("body").ready(function()
     {
       $.ajax(
          {
            url: '/Data.php',
            type: 'GET'
            success: function(text)
                {
                     response=text;
                }
          });
     });
    $("body").append("<select> /*Get values here as options*/ </select>");
 });

但所需的操作是逐行获取值,例如:- 第一行值来了-> 在 jquery 中采取某些行动; 第二行值来了-> 采取某些行动..; . . 以此类推。

【问题讨论】:

  • 那么,你的 Ajax 请求在哪里???
  • @Mr.NaViD.. 哦对不起先生我的错误。让我包括那个......
  • 不要在 Ajax 成功之外使用 append(),而是尝试在 Ajax 成功中使用它
  • @Mr.NaViD...先生,我试过了,它接受整张桌子作为一种选择......

标签: php jquery mysql ajax


【解决方案1】:

数据.php

<?php

$con=@mysqli_connect("","root","root","DBTemp");

# Instead of that use header 500 to let javascript side know there is a real error.

if (mysqli_connect_errno())
{
    echo "Could not connect to database : ". mysqli_connect_error();
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    exit();
}


$sql="select * from Subject";

$result = mysqli_query($con,$sql);

if (mysqli_error($con))
{
    echo "Query failed : ".mysqli_error($con);
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    exit();
}

$options = array();

# populate options arrey with using table's id field as key 
# and subject field as value.

while($row = mysqli_fetch_assoc($result))
{
    $options[$row['id']] = $row['subject'];

}

# return json encoded array to parse from javascript.
echo json_encode($options);

Data.php 将输出:

{"1":"Subject ID 1","2":"Subject ID 3"}

Jquery.js

$(document).ready(function()
{

    $("body").ready(function()
    {
        $.ajax(
                {
                    url: '/Data.php',
                    type: 'GET',
                    dataType: 'json',  // Let jQuery know returned data is json.
                    success: function(result)
                    {
                        $.each(result, function(id, subject) {
                            # Loop through results and add an option to select box.
                            $("#ajaxpopulate").append( new Option(subject,id) )
                        });

                    }
                });
    });

});

Page.html ,在正文中。此选择框将从 ajax 请求中填充。

 <select id="ajaxpopulate"></select>

【讨论】:

  • 谢谢先生。这就是我想要的答案。
  • 先生,如果喜欢已经存在于选择框中,我想删除所有值(从 json 数组接收)怎么办?
  • 你可以循环选择框选项:$('#ajaxpopulate').each(function(){});,如果它已经存在,你可以继续。
【解决方案2】:

我会让 php 函数返回一个 json 响应。您可以通过两种方式执行此操作,或者通过您的 while 语句服务器端手动构造 JSON,或者使用 json_encode PHP 函数并回显该服务器端。这样,当数据在 ajax 响应中返回客户端时,您可以将 JSON 数据解析为 JSON 对象JSON.parse(json);,然后以结构化方式逐行控制数据。

希望这会有所帮助!

【讨论】:

  • 先生,如果我想删除所有值(从 json 数组接收),如果选择框已经存在?
  • 我相信您可以在前端为此进行必要的检查,或者更好的是,如果它们已经存在,您可以在后端进行检查。
【解决方案3】:

1) 您需要使用像数组这样的数据结构并将其作为 json 响应传递给您的 ajax 调用。 2) 您需要遍历您的 json 数组,这样您就可以分别处理每一行并创建嵌套选择选项。

更新

$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: " 
.mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
$jsonResult = [];
while($row = mysqli_fetch_assoc($result))
{
$jsonResult[] = $row["SUBJECT"];
}
echo json_encode($jsonResult);

一个 jquery 应该是这样的

$(document).ready(function()

{
var response='';
$("body").ready(function()
 {
   $.ajax(
      {
        url: '/Data.php',
        type: 'GET'
        dataType : 'JSON',
        success: function(data)
            {
                 //Alert should return an array of your subjects
                 //If it does then you need to iterate through this array and create options manually.
                 alert(data);
            }
      });
 });
$("body").append("<select> /*Get values here as options*/ </select>");

});

【讨论】:

  • 先生,您能给我一个示例代码,以便我可以正确理解。谢谢
  • 先生,如果喜欢已经存在于选择框中,我想删除所有值(从 json 数组接收)怎么办?
猜你喜欢
  • 2014-05-03
  • 1970-01-01
  • 2016-01-15
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 2013-02-03
相关资源
最近更新 更多