【问题标题】:show div if php echo is empty: Ajax如果 php echo 为空,则显示 div:Ajax
【发布时间】:2019-07-17 13:49:38
【问题描述】:

快速提问。

我有以下。

<script>
$(function () {
$('form').on('submit', function(e){
   e.preventDefault();
   $.ajax({
        type: 'post',
        url: 'search/searchpost.php',
        data: $('form').serialize(),
        success: function(data) {
            $('#results').html(data);
            $('#default').hide();
        }
     });
  });
 });
 </script>

这很好用,但如果回显不包含任何内容,我希望它显示#default div 而不是隐藏它。这可能吗?

PHP 页面

<?php
require_once('../config/db.php');
require_once('../customLIB/pdo_db.php');
require_once('../models/test.php');
$SalesRep = new SalesRep();

if ($_POST['search']) {
$data = $_POST['search'];
$rep = $SalesRep->getRep($data);

if(!empty($rep)) {

    echo "
     <div class='modal-body clearfix row'>
        <div class='col-md-4 text-center'><img     src='img/salesmap/image.jpg'  alt='Name' /></div>
        <div class='col-md-8 salesman'>
            <h2>Name</h2>
            <p class='salesman-subtxt'>Subtext</p>
            <p class='salesman-phone'><br />
                Office: <br />
                Cell: <br />
                Email: <a href='' target='_blank'></a></p>
        </div>
    </div>";

 }
}
?>

【问题讨论】:

  • if (data == "") doSmth()
  • 非常感谢,将其作为答案,我会接受。

标签: php jquery ajax


【解决方案1】:

由于在某些参数未设置的情况下不回显任何内容,data 的值为空字符串(您可以使用console.log(data) 检查它),所以:

success: function(data) {
    if (data != "") {
        $('#results').html(data);
        $('#default').hide();
    } else {
        $('#default').show();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2016-06-09
    • 2016-03-08
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多