【问题标题】:How do I check PHP data with jQuery AJAX?如何使用 jQuery AJAX 检查 PHP 数据?
【发布时间】:2020-06-28 19:16:32
【问题描述】:

我有一个带有 else 语句的 PHP 页面,它通过用户输入从 SQL 数据库中过滤掉数据;这是一些伪代码:

NextPage.php

    //Include database configuration file
    include('../dbConfig.php'); 

    if(isset($_POST['pageno']) || isset($_POST['FetchFilters'])) {

        $limit = 10;    
        $pageno = $_POST['pageno'];
        $offset = !empty($pageno) ? $pageno: 1;

        $SQL = "

            SELECT * FROM list WHERE wt >= 2.5

        ";

        if($pageno >= 1) {


            if(isset($_POST["shape"])) {

                $shape_filter = implode("','", $_POST["shape"]);

                $SQL .= "

                    AND stoneshape IN('".$shape_filter."') 

                ";
            }

            if(isset($_POST["color"])) {

                $color_filter = implode("','", $_POST["color"]);

                $SQL .= "

                    AND stonecolor IN('".$color_filter."')

                ";

            }

            $SQL .= "

                ORDER BY wt ASC
                LIMIT 
                    $offset,
                    $limit

            ";

            $result = mysqli_query($db, $SQL);

            $output = '';

            if(isset($_POST["shape"]) && isset($_POST["color"]) && $row = mysqli_fetch_array($result)) {

                while($row = mysqli_fetch_array($result)) {

                    $output .=  '

                        <div class="Listing">

                            <!-- landing page -->
                            <a href="#ItemPage" class="ItemLink">

                                //Item Information goes here

                            </a>

                        </div>

                    ';

                }

            }

        } else {

            $output = '

                <h1 class="Error">
                    NO DATA MATCHES THAT
                </h1>

            ';

        }

        echo $output;

    }

?>

然后我有一个 AJAX 调用,当图像(inView 中的 ID 为#Loader)时分页;这是它的伪代码:

InfiniteScroll.js

$(document).ready(function(){

    $('#Loader').on('inview', function(event, isInView) {

        if (isInView) {

            //Pagination    
            var nextPage = parseInt($('#pageno').val()) + 1;

            //Filters
            var shape = get_filter('shape');
            var color = get_filter('color');

            $.ajax({

                type: 'POST',
                url: 'vendors/php/NextPage.php',
                data: {
                    pageno: nextPage,
                    shape: shape,
                    color: color
                },
                async: true,
                cache: false,
                error: 

                    function(jqXHR, strError) {

                        if(strError == 'timeout') {

                            // Do something. Try again perhaps?
                            alert('Seems like there was an error loading the next page.');

                        }

                    },

                success: 

                    function(data) {

                        $('#Container').append(data); //Container where the NextPage.php data appends to
                        $('#pageno').val(nextPage);

                        if(data != '') { //Here is where my question lyes
                            $('.Error').hide();     //Else statement on NextPage.php should 'hide' as there is data to show
                            $('#Loader').show();    //Show image for pagination
                        } else {
                            $('.Error').show();     //Else statement on NextPage.php should 'show' as there is data to show
                            $('#Loader').hide();    //Hide image for pagination 
                        }

                    },

                timeout: 3000

            });

        }

    });

});

//Gets values of filters for filters variables
function get_filter(class_name) {

    var filter = [];

    $('.'+class_name+':checked').each(function() {
        filter.push($(this).val());
    });

    return filter;

}

我的问题是 NextPage.php 上的 else 语句被视为数据,所以我不知道如何检查 $row 是否正在显示。当有$row(s) 显示其他hide #Loader 和show .Error 时,我希望.Error 类为hide。如何在我的 AJAX 调用中检查 .Error?

【问题讨论】:

  • 您应该考虑将数据返回为 JSON,而不是 HTML。然后使用模板将其添加到站点。要返回错误检查此stackoverflow.com/questions/4417690/…
  • 您的 SQL 容易受到 SQL 注入攻击。您应该使用参数化查询,因为您已经在使用 mysqli。
  • @scragar 解决这个问题后,我将使用this 教程帮助我设置参数。我只是不喜欢同时处理两个问题。这让我很困惑哈哈
  • @ariel 出于好奇(我对这一切都很陌生)将数据返回为 HTML 有什么问题?

标签: javascript php jquery ajax pagination


【解决方案1】:

在没有更多 data 时隐藏 #Loader 计算 SQL 行的总迭代次数,并将其作为 PHP 变量放在当前迭代旁边。然后,我将这两个变量放在 PHP 的 while 语句中的隐藏输入中,并使用 jQuery 将每个输入属性放入一个变量中,然后我可以检查数字是否匹配,如果匹配,我将隐藏 #Loader。

至于错误(PHP 的 else 语句),我检查了数据是否具有 .Error 类,如果是,我将隐藏 #Loader。

这是伪代码:

SQL 查询(窗口函数仅适用于 MySQL 8.0+)

...
    SELECT inv.*, COUNT(*) OVER() AS totalrows FROM list inv WHERE wt >= 2.5
...

NextPage.php

...
    $ListingCounter = 0; // Begin counting iterations of while loop

    $Output = '';

        if($RowCount > 0) {

            while($row = mysqli_fetch_array($MySQLiQuery)) {

                $ListingCounter++; // Count iterations
                $ListingCount = $ListingCounter + $Offset; // Continue counting iterations after $Limit

                $output .=  '

                        <div class="Listing">

                            <!-- landing page -->
                            <a href="#ItemPage" class="ItemLink">

                                //Item Information goes here

                            </a>

    <input id="StoneIteration" type="hidden" data-listing="'echo $ListingCount;'" data-totalrows="'echo $row['totalrows'];'">


                        </div>

                    ';
...

InfiniteScroll.js

...

success: 

    function(data) {

        $('#Container').append(data);
        $('#PageNo').val(NextPage);

        // If the hidden input inside each .Stone's data attributes content both match hide #Loader
        $('.Listing').each(function(index, element) {

            var TotalRowCount = $(element).find('[data-totalrows]').data('totalrows');
            var ListingCount = $(element).find('[data-listing]').data('listing');

            if(TotalRowCount != ListingCount) {
                $('#Loader').show();   // Show infinite scroll
            } else {
                $('#Loader').hide();   // Hide infinite scroll
            }

        });

        // If data has .Error hide #Loader
        if(data.indexOf('class="Error"') > -1) {
            $('#Loader').hide();   // Hide infinite scroll
        }

    }
...

我希望这对某人有所帮助。有什么问题欢迎追问!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 2016-12-03
    • 2012-08-08
    • 2017-06-04
    • 2012-02-21
    • 2013-09-29
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多