开发者

Display message when no HTML is returned to jQuery search script

I have a Google Instant style search script written in jQuery which queries a PHP file. Currently, when no results are found, the PHP file returns no HTML code so the script is blank. How can I make it so my jQuery script displays a message when no HTML code is returned?

My code jQuery code is:

$(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"开发者_如何学Python).html(response);
            }
        });
    });
});


Change this line

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

To

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

Hope this helps.


The easy answer is:

If the reponse is empty it's length should be zero.

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

The more complicated answer is: I usually solve these kinds of issues a bit more explicit, by encoding my reponse in json. Therefor I always have an object which is something like this:

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

This will allow you to send messages back and forth a bit more confortable and explicit from your php.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜