2011-06-05 31 views
0

我有一個用jQuery編寫的查詢PHP文件的Google即時樣式搜索腳本。目前,當沒有找到結果時,PHP文件不會返回HTML代碼,因此腳本爲空。我怎麼做到這一點,所以當沒有HTML代碼返回時,我的jQuery腳本顯示一條消息?當沒有HTML返回到jQuery搜索腳本時顯示消息

我的代碼jQuery代碼是:

$(document).ready(function(){ 
    $("#search").keyup(function(){ 
     var search=$(this).val(); 
     var query=encodeURIComponent(search); 
     var yt_url='search.php?q='+query+'&category=web'; 
     window.location.hash='search/'+query+'/1/'; 
     document.title=$(this).val()+" - My Search Script"; 
     if(search==''){ 
      window.location.hash=''; 
      document.title='My Search Script'; 
     } 
     $.ajax({ 
      type:"GET", 
      url:yt_url, 
      dataType:"html", 
      success:function(response){ 
       $("#result").html(response); 
      } 
     }); 
    }); 
}); 

回答

1

改變這一行

$("#result").html(response); 

if(response != "") 
    $("#result").html(response); 
else 
    $("#result").html("No html returned."); 

希望這有助於。

0

最簡單的答案是:

如果是效應初探空它的長度應爲零。

 success:function(response){ 
      if (response.length == 0) 
      { 
       // no result 
      } else { 
       $("#result").html(response); 
      } 
     } 

更復雜的答案是: 我通常更明確一點,在JSON編碼我的效應初探解決這類問題。爲此我始終有一個對象,它是這樣的:

{ 
    result: ... (any kind of result, data, html, etc.), 
    error: 'error messages, 
    notice: 'notice messages 
} 

這將允許你從你的php發送郵件來回多一點舒適和清晰。