如何使用jquery检查json数据返回是否为空


How to check if json data return is empty with jquery

我有一个实时搜索器,当它的数据显示时如果数据为空,我需要发出警报

这是jquery:

$(document).ready(function() {
        $('#q').on('input', function() {
            var searchKeyword = $(this).val();
            if (searchKeyword.length >= 3) {
                $.post('/files/assets/php/ajax/search.php', { q: searchKeyword }, function(data) {
                    $('ul#content').show();
                    $('ul#content').empty()
                    $.each(data, function() {
                         if ( data.length == 0 ) {
                        $('ul#content').append('<li style="text-align: center;font-weight:bold;"><font color="white">empty</font></a></li>');
                        }else{
$('ul#content').append('<li style="text-align: center;font-weight:bold;"><a href="/store/' + this.id + '/' + this.seo + '"><font color="white">' + this.title + '</font></a></li>');
                        }
                    });
                }, "json");
            }
        });
    });

和 PHP:

$conexion = mysqli_connect($serv,$user,$pass,$base);
$arr = array();
if (!empty($_POST['q'])) {
    $keywords = $Main->limpiar($_POST['q']);
    $mysqli = $conexion;
    $result = $mysqli->query("SELECT cat, titulo FROM pinturas WHERE titulo LIKE '%".$keywords."%' OR cat LIKE '%".$keywords."%'");
    if ($result->num_rows > 0) {
        while ($obj = $result->fetch_array()) {
            $seo =  str_replace(" ","_",$obj['titulo']);
            $arr[] = array('id' => $obj['cat'], 'title' => $obj['titulo'], 'seo' => $seo);
        }
    }else{
        $arr[] = array('id' => '', 'title' => '', 'seo' => '');
        }
}
echo json_encode($arr);

我想如果数据为空,则显示附加为空

但它不起作用

假设数据是 JSON 解析的对象,您可以:

Object.keys(data).length === 0

JSON.stingify(data) === '{}'

在迭代前检查记录的长度(在 jquery API 中使用 $.each)

    <script>
    $(document).ready(function () {
        $('#q').on('input', function () {
            var searchKeyword = $(this).val();
            if (searchKeyword.length >= 3) {
                $.post('/files/assets/php/ajax/search.php', { q: searchKeyword }, function (data) {
                    console.log(data);
                    $('ul#content').show();
                    $('ul#content').empty()
                    if (data.length == 0) {
                        $('ul#content').empty().append('<li style="text-align: center;font-weight:bold;"><font color="white">empty</font></a></li>');
                    }
                    else {
                        $.each(data, function () {
                            $('ul#content').append('<li style="text-align: center;font-weight:bold;"><a href="/store/' + this.id + '/' + this.seo + '"><font color="white">' + this.title + '</font></a></li>');
                        });
                    }
                });
            }
        });
    });
</script>

为我工作。

希望这有帮助。