简单的jQuery if语句,API返回'null'

时间:2015-04-27 15:21:13

标签: 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.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>');
        }
    });

});
});

1 个答案:

答案 0 :(得分:1)

myFolks += (rep.nickname && rep.nickname !== "null") ? rep.nickname : rep.first_name + ' ';

via:@tomcreighton