当没有HTML返回到jQuery搜索脚本时显示消息

时间:2011-06-05 21:32:59

标签: javascript jquery html

我有一个用jQuery编写的Google Instant样式搜索脚本,用于查询PHP文件。目前,当找不到结果时,PHP文件不返回HTML代码,因此脚本为空。如何在没有返回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);
            }
        });
    });
});

2 个答案:

答案 0 :(得分:1)

更改此行

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

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

希望这有帮助。

答案 1 :(得分: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中来回发送更加容易和明确的消息。

相关问题