获取未捕获的TypeError:无法使用' in'运营商搜索'长度'在

时间:2016-02-25 18:37:28

标签: javascript php json wordpress

我想自动将提取的类型从IMDB添加到我的类别。我为我做了JSON代码。

    $('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/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg","Metascore":"80","imdbRating":"9.3","imdbVotes":"1,610,411","imdbID":"tt0111161","Type":"movie","Response":"True"}

一切正常。我的意思是Actors,Director和Casts会自动添加。我的问题在于流派。

我发现了这个错误:

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

我的JQuery版本是2.2.1。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

JSON中的"Genre"字段如下所示:

"Genre":"Crime, Drama"

这是一个包含两个逗号分隔的单词的字符串。 不是包含两个字符串的数组。您无法使用$.each迭代单个字符串。

您需要先使用String.split()将字符串拆分为字符串数组:

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

这使用regular expression在每个逗号分隔Genre字符串(包括可能的空格)。结果是一个数组["Crime", "Drama"] $.each可以迭代。