7

Я попытался извлечь данные с помощью facebook api на входные данные формы. Теперь все прошло отлично, пока я не попытался найти местоположение текущего пользователя.Uncaught TypeError: Не удается прочитать свойство 'name' of undefined

Если текущий пользователь поделился своим местоположением (где он живет), то у меня не возникнет проблем. Однако, если пользователь не поделился своим местоположением на facebook, я получаю сообщение об ошибке: Uncaught TypeError: Cannot read property 'name' of undefined

Вот код, который я использовал. Если у вас есть какие-либо идеи, как решить эту проблему, пожалуйста, комментарий здесь :)

<div id="fb-root"></div> 
<script> 
    // Additional JS functions here 
    window.fbAsyncInit = function() { 
    FB.init({ 
     appId  : '*******', // App ID 
     status  : true, // check login status 
     cookie  : true, // enable cookies to allow the server to access the session 
     xfbml  : true // parse XFBML 
    }); 

    FB.getLoginStatus(function(response) { 
    if (response.status === 'connected') { 

    FB.api('/me', function(response) { 
    document.getElementById("user_login").value="FB - " + response.username; 
    document.getElementById("user_email").value=response.email; 
    document.getElementById("first_name").value=response.first_name; 
    document.getElementById("last_name").value=response.last_name; 
    document.getElementById("user_url").value=response.link; 
    document.getElementById("fbid").value=response.id; 
    if(response.location !== 'undefined') 
    { 
    document.getElementById("location").value=response.location.name; 
    alert(response.location.name); 
    } 
    document.getElementById("registerform").submit(); 

}); 

    } else if (response.status === 'not_authorized') { 
    alert('error'); 
    } else { 
    alert('Please Log In!'); 
    } 
}); 

    }; 

    // Load the SDK Asynchronously 
    (function(d){ 
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; 
    if (d.getElementById(id)) {return;} 
    js = d.createElement('script'); js.id = id; js.async = true; 
    js.src = "//connect.facebook.net/en_US/all.js"; 
    ref.parentNode.insertBefore(js, ref); 
    }(document)); 
</script> 

ответ

16

На этой линии:

if(response.location !== 'undefined') 

... вы проверяете, если response.location не строка"undefined". Поскольку undefined не является строкой "undefined", условие истинно. Затем вы пытаетесь использовать response.location.name, а response.location - undefined, вы получаете ошибку.

вероятно Вы имели в виду либо:

if(response.location) 

или

if(typeof response.location !== 'undefined') 
+0

Спасибо! Моя ошибка ... –

+0

@ IdoDoron: Не стоит беспокоиться, рад, что помог! Легкая ошибка. –

Смежные вопросы