Javascript 简单的jQuery if语句,API返回';空';
使用Sunlight Congress API获取代表列表,我想返回人们的昵称,如果他们被使用的话。如果代表不使用昵称,API将返回“null” 我弄乱了if语句的语法。以下是我最近的错误做法:Javascript 简单的jQuery if语句,API返回';空';,javascript,jquery,Javascript,Jquery,使用Sunlight Congress API获取代表列表,我想返回人们的昵称,如果他们被使用的话。如果代表不使用昵称,API将返回“null” 我弄乱了if语句的语法。以下是我最近的错误做法: if (rep.nickname == 'null'){myFolks += rep.first_name + ' ';} 以下是完整的上下文: $(document).ready(function () { $('#rep-lookup').submit(function(e){ e.pr
if (rep.nickname == 'null'){myFolks += rep.first_name + ' ';}
以下是完整的上下文:
$(document).ready(function () {
$('#rep-lookup').submit(function(e){
e.preventDefault();
var $results = $('#rep-lookup-results'),
zipcode = $('#txt-zip').val(),
apiKey = '_YOUR_API_KEY';
var requestURL = 'http://congress.api.sunlightfoundation.com/legislators/locate?callback=?';
// collect the data
$.getJSON(requestURL, {
'apikey' : apiKey,
'zip' : zipcode,
}, function(data){
if (data.results && data.results.length > 0) {
var myFolks = '<p>Here are your Congress folk:</p>';
$.each(data.results, function(i, rep) {
myFolks += '<p>';
myFolks += '<a href="' + rep.contact_form + '" target="_blank">';
myFolks += rep.nickname;
if (rep.nickname == 'null'){myFolks += rep.first_name + ' ';}
myFolks += rep.last_name + ' ';
myFolks += '</a>';
myFolks += '</p>';
});
myFolks += '<p>Please write to them in support of this legislation.</p>';
$results.html(myFolks);
} else {
$results.html('<p>None found for zip code ' + zipcode + '. Please try again.</p>');
}
});
});
});
$(文档).ready(函数(){
$('#rep lookup')。提交(函数(e){
e、 预防默认值();
var$results=$(“#代表查找结果”),
zipcode=$('#txt zip').val(),
apiKey=''u你的API'u键';
var requestURL=http://congress.api.sunlightfoundation.com/legislators/locate?callback=?';
//收集数据
$.getJSON(请求URL{
“apikey”:apikey,
“zip”:zipcode,
},函数(数据){
if(data.results&&data.results.length>0){
var mypeops='这是你的国会议员:;
$.each(data.results,function(i,rep){
MyPeople+='';
我的家人+='';
MyPeople+='';
});
MyPeople+='请写信给他们支持这项立法。';
$results.html(mypeops);
}否则{
$results.html(“未找到邮政编码“+zipcode+”。请重试。”;
}
});
});
});
via:@tomcreighton您确定API返回字符串
“null”
?它可能会返回null
对象。此外,在您检查它是否存在之前,您正在使用它mypeops+=(rep.nickname&&rep.nickname!=“null”)?代表昵称:代表名字+“”代码>?@FrédéricHamidi,你说得对。它返回的是对象而不是字符串。通过去掉引号,我可以得到你的名字。现在,当代表没有昵称时,我需要从输出中获取“null”。可能有点像另一个if…Thnx,@tomcreighton,行得通!我需要习惯一行if语句。
myFolks += (rep.nickname && rep.nickname !== "null") ? rep.nickname : rep.first_name + ' ';