[英]How to check array is empty and display message in content in Ajax?
代码中发生的事情是,我们基于单选按钮单击显示一个RSS feed。 每个单选按钮的RSS提要并不总是具有内容,我希望在空白屏幕上显示一条消息。 谢谢!
<script type="text/javascript">
$(document).ready(function() {
$('input[type=radio]').click(function() {
var id = this.id;
if(id == 'radio-bio') { var categoryURL = '/BayAreaTech/wp-rss2.php?cat=15';}
else if (id == 'radio-com'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=13';}
else if (id == 'radio-eleP'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=9';}
else if (id == 'radio-eleD'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=10';}
else if (id == 'radio-nano'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=16';}
else if (id == 'radio-opt'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=12';}
else if (id == 'radio-semi'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=11';}
else if (id == 'radio-comSoft'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=14';}
else if (id == 'radio-techMan'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=17';}
else { var categoryURL = '/BayAreaTech/wp-rss2.php?cat=1';}
$('#feedContainer').empty();
$.ajax({
type: 'GET',
url: categoryURL,
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item:lt(40)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region.length < 3) { region = "SF"; }
var description = $(this).find("description").text();
var infoDisplay = description.substr(0, description.indexOf(",")+120) + "..."; //Parsed DATE from description
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
var item = {title: displayTitle, infoDecription: infoDisplay, Date: new Date(eventDate), Region: region,}
var now = moment();
if (item.Date >= now){ data.push(item); }
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
});
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a<b ? -1 : a>b ? 1 : 0;
});
$.each(data, function (index, item) {
$('#feedContainer').append('<h3>' + item.title + '</h3><p>' + item.infoDecription + '</p>');
});
}
});
$("#fieldpanel").panel("close");
});
});
</script>
您可以检查数组的长度
if (data.length > 0) {
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a<b ? -1 : a>b ? 1 : 0;
});
$.each(data, function (index, item) {
$('#feedContainer').append('<h3>' + item.title + '</h3><p>' + item.infoDecription + '</p>');
});
}
else {
$("#feedContainer").append('<h3>There is no content to display</h3>');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.