简体   繁体   English

使用Ajax从mysql表中检索数据

[英]Retrieve data from mysql table using ajax

I'm trying to show MySQL data using Ajax. 我正在尝试使用Ajax显示MySQL数据。 Unfortunately, I am unable to find the correct way. 不幸的是,我找不到正确的方法。 I was trying to show MySQL data on a select box. 我试图在选择框上显示MySQL数据。 When I click on "select category" option then all category will show as dropdown. 当我单击“选择类别”选项时,所有类别将显示为下拉列表。

here is my HTML code.

<!DOCTYPE html>
 <html>
 <head>
 <title>PHP MySQL Insert Tutorial</title>
 <script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
 </head>

 <body>
 <select id='category'>

 </select>
 <script src='fetch.js'></script>
 </body>
</html>

I have used this JS code to send request. 我已使用此JS代码发送请求。 Here is my JS code. 这是我的JS代码。

$('#category').onclick(function(){
     $.getJSON(
         'fetch.php',

         function(result){
             $('#category').empty();
             $.each(result.result, function(){
             $('#category').append('<option>'+this['category']+'</option>');
             });
         }
     );
});

I have used this php code to complete ajax request and database connection. 我已经使用此php代码完成了ajax请求和数据库连接。 Here is my PHP code. 这是我的PHP代码。

<?php
 define('HOST','localhost');
 define('USERNAME', 'root');
 define('PASSWORD','');
 define('DB','ajax');

 $con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);

 $category = $_GET['category'];

 $sql = "select category from ajaxx where category='$category'";

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

 $result = array();

 while($row = mysqli_fetch_array($res)){
 array_push($result, 
 array('category'=>$row[0]));
 }

 echo json_encode(array('result'=>$result));


    enter code here

 mysqli_close($con);
?>

When you make the AJAX request, it's to this URL: 当您发出AJAX请求时,它就是以下URL:

fetch.php

But then in the server-side code, you try to get a query string value: 但是,然后在服务器端代码中,您尝试获取查询字符串值:

$category = $_GET['category'];

You can't get a query string value that you never provided. 您无法获得从未提供的查询字符串值。 So when you build your SQL query (which is wide open to SQL injection by the way), there's nothing to get from the database. 因此,当您构建SQL查询时(顺便说一句,它对SQL注入开放的),从数据库中就没有任何可获取的东西。

If you want to use a query string value, you have to provide one : 如果要使用查询字符串值,则必须提供一个

$.getJSON(
     'fetch.php?category=someValue',
     function(result){
         //...
     }
 );

What value you provide or where you get that value is up to you. 您提供什么价值或从哪里获得价值取决于您。 (Perhaps from $('#category').val() ?) But it has to exist before you can use it. (也许来自$('#category').val()吗?)但是它必须存在才能使用。

You may have confused two things: (a) initially fetching the HTML code to populate the options of your <select> control, and (b) Catching the selected option and using it to perform another DB query, returning new data. 您可能已经混淆了两件事:(a)最初获取HTML代码以填充<select>控件的选项,以及(b)捕获所选选项并使用它执行另一个DB查询,返回新数据。

Please review this modified (untested) code sample: 请查看以下修改(未试用)的代码示例:

<!DOCTYPE html>
 <html>
 <head>
 <title>PHP MySQL Insert Tutorial</title>
 <script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
 </head>

 <body>
 <select id='category'>

 </select>
 <div id="resultDIV"></div>
 <script src='fetch.js'></script>
 </body>
</html>

javascript/jQuery: javascript / jQuery:

    //Run on document ready to populate the dropdown box
    $(document).ready(function(){
    $.getJSON(function(){
        'fetch.php',
        function(result){
            $('#category').empty();
            $.each(result.result, function(){
                $('#category').append('<option>'+this['category']+'</option>');
            });
        }
    });

    $(document).on('click', '#category', function(){
        //run on click to take dropdown value and perform lookup
        myCat = $(this).val();
        $.ajax({
            type: 'post',
             url: 'getcategory.php',
            data: 'category=' +myCat,
            success: function(d){
                //if (d.length) alert(d);
                $('#resultDIV').html(d);
            }
        });
    });

}); //END document.ready

I have used this php code to complete ajax request and database connection. 我已经使用此php代码完成了ajax请求和数据库连接。 Here is my PHP code. 这是我的PHP代码。

<?php
    /*** getcategory.php ***/

    define('HOST','localhost');
    define('USERNAME', 'root');
    define('PASSWORD','');
    define('DB','ajax');

    $con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);

    $category = $_GET['category'];

    $sql = "select category from ajaxx where category='$category'";

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

    $result = array();

    while($row = mysqli_fetch_array($res)){
    array_push($result, 
    array('category'=>$row[0]));
    }

    echo json_encode(array('result'=>$result));


    enter code here

    mysqli_close($con);
?>

Here are some basic, simple AJAX examples to study (the three links at the bottom, but also note the information from the first link). 这里是一些简单的基本AJAX示例(底部的三个链接,但也请注意第一个链接的信息)。 Copy them to your server and make them work - play around with them: 将它们复制到您的服务器并使它们工作-与它们一起玩:

AJAX request callback using jQuery 使用jQuery的AJAX请求回调

Your ajax code needs some changes : 您的ajax代码需要进行一些更改:

<!DOCTYPE html>
 <html>
 <head>
 <title>PHP MySQL Insert Tutorial</title>
 <script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
 <script type="text/javascript">
function myAjax ()
{ $.ajax( { type    : 'POST',
            data    : { 'category' : $('#txt_cat').val() }, // SEND CATEGORY.
            url     : 'fetch.php',
            success : function ( result )
                      { $( '#category' ).empty();
                        var arr = JSON.parse( result );
                        var sel = document.getElementById("category");
                        for ( i = 0; i < arr.length; i++ )
                        { var option = document.createElement( "option" );
                          option.text = arr[ i ];
                          sel.add( option );
                        }
                      },
            error   : function ( xhr )
                     { alert( "error" );
                     }
          }
        );
}
 </script>
 </head>
 <body>
   Enter category <input type="text" id="txt_cat"/>
   <button onclick="myAjax()">Click here to fill select</button>
   <select id='category'>
     <option> - empty - </option>
   </select>
 </body>
</html>

fetch.php fetch.php

<?php
$category = $_POST[ "category" ];           // CATEGORY FROM HTML FILE.
// CONNECT TO DATABASE AND QUERY HERE.
$result = Array( "111","222","333","444" );  // SAMPLE DATA.
echo json_encode( $result );
?>

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

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