2010-11-22 37 views
0

如果沒有返回空值,此代碼將很好地工作。但是我在測試過程中注意到,如果任何值爲null,那麼它會拋出錯誤並打破腳本的其餘部分。Facebook API返回null,如何在Javascript中跳過它

我該如何跳過值如果爲空,或將其設置爲別的東西。

function fqlQuery(){ 
       FB.api('/me', function(response) { 
        var query = FB.Data.query('SELECT uid, first_name, last_name, email, sex, pic_square, timezone, birthday_date, current_location FROM user WHERE uid = me()', response.id); 
        query.wait(function(rows) { 
         fb_uid = rows[0].uid; 
         first_name = rows[0].first_name; 
         last_name = rows[0].last_name; 
         sex = rows[0].sex; 
         email = rows[0].email; 
         fb_pic_square = rows[0].pic_square; 
         timezone = rows[0].timezone; 
         birthday_date = rows[0].birthday_date; 
         current_city = rows[0].current_location.city; 
         current_country = rows[0].current_location.country; 
         $.ajax({ 
          type: "POST", 
          url: "postdb.php", 
          data: "first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&fb_uid=" + fb_uid + "&sex=" + sex + "&fb_pic_square=" + fb_pic_square + "&timezone=" + timezone + "&birthday_date=" + birthday_date + "&current_city=" + current_city + "&current_country=" + current_country, 

    success: function(msg){ 
    alert("Data Saved: " + msg); 
    } 

         }); 



        }); 

       }); 

在此先感謝。

回答

0
var foo = rows[0].foo || ""; 

將返回""(空字符串),如果rows[0].foo爲null。

+0

我剛剛試過你的建議。仍然得到相同的結果。 rows [0] .current_location爲空 [此錯誤中斷] current_city = rows [0] .current_location.city || 「」; – kkampen 2010-11-22 15:49:27

0

我修正了這個問題。

if(rows[0].current_location != null){ 
    current_city = rows[0].current_location.city || ""; 
    current_country = rows[0].current_location.country || ""; 
}