简体   繁体   English

如何使用jQuery(AJAX)从mysql表中逐行获取数据,用php编码的查询?

[英]How to fetch data row by row from mysql table, queries coded in php, using jquery (AJAX)?

I am a beginner in Ajax. 我是Ajax的初学者。 I want to fetch data row from Subject Table consist of only one column Subject as varchar(100), defined in MySQL DB. 我想从主题表中获取仅由一列主题组成的数据行,主题为varchar(100),在MySQL DB中定义。 Following is my php code. 以下是我的PHP代码。

Data.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 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>");
 });

But The Desired action is getting values row by row like:- 1st row value comes-> take certain action in jquery; 但是Desired动作是逐行获取值,例如:-第一行值来了->在jquery中采取某些动作; 2nd row value comes-> take sertain action..; 第二行值来->采取某些措施。 . . so on. 以此类推。

1) You need to use data structure like an array and pass it as a json response to your ajax call. 1)您需要使用数据结构(例如数组),并将其作为json响应传递给您的ajax调用。 2) You need to iterate through your json array and that is where you can process each row separately and create nested select options. 2)您需要遍历json数组,在这里您可以分别处理每一行并创建嵌套的选择选项。

UPDATE 更新

$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);

An jquery should look like this 一个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>");

}); });

I would have the php function return a json response. 我会让php函数返回一个json响应。 You could do this in two ways either construct the JSON manually through your while statement server side or use the json_encode PHP function and echo that server side. 您可以通过两种方式执行此操作,或者通过while语句服务器端手动构造JSON,或者使用json_encode PHP函数并回显该服务器端。 That way when the data is returned client side in your ajax response you can parse the JSON data to a JSON object JSON.parse(json); 这样,当在ajax响应中客户端返回数据时,您可以将JSON数据解析为JSON对象JSON.parse(json); and then control row by row the data in a structured way. 然后以结构化的方式逐行控制数据。

Hope this helps! 希望这可以帮助!

Data.php 数据.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 will output : Data.php将输出:

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

Jquery.js 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 , inside the body. Page.html,在体内。 This select box will populated from ajax request. 此选择框将从ajax请求中填充。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM