Reputation: 2933
I'm doing an ajax lookup using jQuery, which is all going swimmingly. However I want to be able to do something special if the lookup itself is successful but returns an empty result. For example I'm using code like this to do the lookup:
jq.ajax({
url: '/getMatches',
dataType: 'json',
data: 'text=' + jq(this).val(),
success: function(data) {
jq.each(data, function(k, v) {
jq('#results ul').append('<li><a href="' + v.url + '">' + v.title + '</a></li>')
});
}
});
If there are results it will look like this:
<div id="results">
<ul>
<li><a href="www.example.com/one">Example one</a></li>
<li><a href="www.example.com/two">Example two</a></li>
<li><a href="www.example.com/three">Example three</a></li>
</ul>
</div>
I'd like to do the following if there are no results:
<div id="results">
<p>There are no results</p>
</div>
I couldn't see anything in the jQuery docs, so how can I do it?
Upvotes: 0
Views: 6372
Reputation: 163238
Assuming that the response data is a JSON array, you can simply check the length
property:
if(!data.length) {
//no results...
return;
}
jq.each(data, function(k, v) {
jq('#results ul').append('<li><a href="' + v.url + '">' + v.title + '</a></li>')
});
Upvotes: 3