簡體   English   中英

如何使用jQuery(AJAX)從mysql表中逐行獲取數據,用php編碼的查詢?

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

我是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>");
 });

但是Desired動作是逐行獲取值,例如:-第一行值來了->在jquery中采取某些動作; 第二行值來->采取某些措施。 以此類推。

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

});

我會讓php函數返回一個json響應。 您可以通過兩種方式執行此操作,或者通過while語句服務器端手動構造JSON,或者使用json_encode PHP函數並回顯該服務器端。 這樣,當在ajax響應中客戶端返回數據時,您可以將JSON數據解析為JSON對象JSON.parse(json); 然后以結構化的方式逐行控制數據。

希望這可以幫助!

數據.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM