通过javascript从LinkedIn API获取结果

时间:2012-05-21 08:17:55

标签: javascript variables undefined linkedin

首先感谢您阅读本文。我在使用javascript获取Linkedin登录API提供的数据时遇到了一些麻烦。这是脚本:

    <script type="text/javascript">
    function onLinkedInAuth() {
    IN.API.Profile("me").fields(["firstName","lastName","headline","summary","location","educations","skills"]).result(displayProfiles);
    }

function displayProfiles(profiles) {
     member = profiles.values[0];
     document.getElementById("name").value = member.firstName +" "+ member.lastName;
     document.getElementById("pos").value = member.headline;
     document.getElementById("city").value = member.location.name;
     document.getElementById("sum").value = member.summary;

     var i=0; 
      do {

            var oldHTML = document.getElementById('para').innerHTML;
            var newHTML = oldHTML + "<tr><td>" + member.educations.values[i].schoolName + "</td></tr>";
            document.getElementById('para').innerHTML = newHTML;
        i++;
      }
      while(i<=1);
      var v=0;
      do {
            var oldHTML = document.getElementById('tara').innerHTML;
            var newHTML = oldHTML + "<tr><td>" + member.skills.values[v].skill.name + "</td></tr>";
            document.getElementById('tara').innerHTML = newHTML;
        v++; 
      }
      while(member.skills.values[v].skill.name);

     document.getElementById("educ").value = member.educations.values[1].schoolName;
     document.getElementById("skills").value = member.skills.values[0].skill.name;
}
</script>

这是获取用户信息的一个非常基本的脚本,其中包括用户的教育和专业背景。问题是member.educations.values [i] .schoolName和member.skills.values [v] .skill.name可以有多个值,我想收集它们。

只要指定的字段不为空,它就会起作用但是它会输出一个错误,说明member.skills.values [v]是未定义的,它不会运行第二个循环。

我知道错误是非常基本的,但我在javascript中并不是那么好。

感谢你的帮助,祝你有个美好的一天!

1 个答案:

答案 0 :(得分:1)

您应该检查返回值的长度,然后根据需要循环遍历它们。有点像:

var educations = member.educations;
if(educations._total > 0) {
  for(var i = 0; i < educations._total; i++) {
    document.getElementById("educ").value += (i > 0) ? ', ' : '';
    document.getElementById("educ").value += educations.values[i].schoolName;
  }
}