2016-02-25 38 views
0

我想從IMDB自動添加提取的流派到我的類別。我讓JSON代碼爲我做這個。獲取未捕獲TypeError:無法使用'in'運算符搜索'長度'

$('input[name=Checkbx]').click(function() { 
    var coc = $('input[name=Checkbx2]').get(0).value; 
    // Send Request 
    $.getJSON("http://www.omdbapi.com/?i=" + coc + "&plot=short&r=json", function(data) { 
     var valDir = ""; 
     var valWri = ""; 
     var valAct = "";  
     $.each(data, function(key, val) { 
       $('input[name=' +key+ ']').val(val); 
       if(key == "Director"){ 
       valDir+= " "+val+","; 
       } 
if(key == "Genre"){ 
      var genr = ""; 
      $.each(data.Genre, function(key, val) { 
       genr += "" + val + ", "; 
       genr1 = val; 
       $('input[name=newcategory]').val(genr1); 
       $('#category-add-submit').trigger('click'); 
       $('#category-add-submit').prop("disabled", false); 
       $('input[name=newcategory]').val(""); 
      }); 
      $('input[name=' +key+ ']').val(genr); 
     } 
       if(key == "Actors"){ 
       valAct+= " "+val+","; 
       } 
       if(key == "Year"){ 
       $('#new-tag-<?php echo get_option('year'); ?>').val(val); 
       } 
       if(key == "Country"){ 
       $('#new-tag-movie-country').val(val); 
       } 
     }); 
     $('#new-tag-<?php echo get_option("director"); ?>').val(valDir); 
     $('#new-tag-<?php echo get_option("actor"); ?>').val(valAct); 
    }); 
}); 

爲了記錄:我使用omdbapi.com API從IMDB得到的數據和測試我的電影ID爲tt0111161和JSON輸出是:

{"Title":"The Shawshank Redemption","Year":"1994","Rated":"R","Released":"14 Oct 1994","Runtime":"142 min","Genre":"Crime, Drama","Director":"Frank Darabont","Writer":"Stephen King (short story \"Rita Hayworth and Shawshank Redemption\"), Frank Darabont (screenplay)","Actors":"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler","Plot":"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","Language":"English","Country":"USA","Awards":"Nominated for 7 Oscars. Another 14 wins & 20 nominations.","Poster":"http://ia.media-imdb.com/images/M/[email protected]_V1_SX300.jpg","Metascore":"80","imdbRating":"9.3","imdbVotes":"1,610,411","imdbID":"tt0111161","Type":"movie","Response":"True"} 

,一切工作正常。我的意思是演員,導演和演員都是自動添加的。我的問題是與流派。

我得到這個錯誤:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in Crime, Drama 

我的JQuery的版本是2.2.1。我怎樣才能解決這個問題?

回答

0

在你的JSON的"Genre"場看起來是這樣的:

"Genre":"Crime, Drama" 

它是一個包含用逗號分隔的兩個單詞的單個字符串。它是而不是一個包含兩個字符串的數組。您無法使用$.each迭代單個字符串。

需要將字符串分割成第一使用String.split()一個字符串數組:

$.each(data.Genre.split(/\s*,\s*/), function(key, val) { 

此使用regular expressionGenre串在每個分割逗號(包括可能的白空間)。結果是["Crime", "Drama"],其中$.each可以迭代。

+0

非常感謝。它的作品就像一個魅力:D ... 另一個問題....例如,我想用另一個字代替這個功能中的「犯罪」..我怎麼能做到這一點? –

相關問題