如果jquery ajax返回数据为空,如何添加判断?

yul*_*ika 2 jquery

我是学习jquery.ajax的新手.我想将一些数据从a.php粘贴到b.php.这是我的代码:

a.php只会

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function () {      
var params = "value=" + $('#send').text();   
$.ajax({        
     url:'b.php',        
     type:'post',                 
     dataType:'html',            
     data:params,  
     success:function(data){  $("#result").html($(data).html('#aa')); }
});
});
</script>
<body>
<div id="result"></div>//sometimes the return data is empty, so this part just return: <div="aa"></div>
<div id="send">apple</div>
Run Code Online (Sandbox Code Playgroud)

b.php

<?php
echo '<div id="aa">';
//'.$_REQUEST['value'].' will put in some process here, but sometimes the return data is empty.
echo '</div>';
?>
Run Code Online (Sandbox Code Playgroud)

如何以及在何处添加判断,如果<div id="aa"></div>为空,则sorry, there is no result在它之间添加

所以a.php,信息将显示:<div id="result"><div id="aa">sorry, there is no result</div></div>

谢谢.

bal*_*dre 7

首先,您应该始终返回DATA/INFORMATION,而不是HTML标签或代码......您在HTML部分中执行此操作.

<?php
//send ONLY the data, best to send in JSON syntax
?>
Run Code Online (Sandbox Code Playgroud)

然后你用

$.ajax({        
     url:'b.php',        
     type:'post',                 
     dataType:'html',            
     data:params,  
     success: function(data) {  

         if(data.length == 0)
             $("#result").html("<span class='no-data'>No Data</span>"); 
         else
         {
             // Loop through the data and add it as, for example an <li> in a <ul>
         }

     }
});
Run Code Online (Sandbox Code Playgroud)