2011-10-05 79 views
1

大家好,並且提前感謝幫助我。首先,如果我在這裏使用錯誤的短語,表示歉意。我不擔心這裏的語法,只是讓這個工作。現在,這個問題:我有Django的串行輸出以下JSON:在Jquery中通過Json迭代

[ 
    { 
     "pk": 11262, 
     "model": "dict.words", 
     "fields": { 
      "lang": "KO", 
      "incorrect": null, 
      "sug_translation": [ 
       3215 
      ], 
      "word": "\uc0dd\uac01\ud558\ub2e4", 
      "definition": [], 
      "pos": "VE", 
      "phrase": [], 
      "translation": [ 
       { 
        "pk": 1, 
        "model": "dict.words", 
        "fields": { 
         "word": "comprender" 
        } 
       }, 
       { 
        "pk": 6028, 
        "model": "dict.words", 
        "fields": { 
         "word": "entender" 
        } 
       } 
      ], 
      "incomplete": null 
     } 
    } 
] 

我希望做的是去fields.translation.fields.words,從而Jquery的的自動完成功能是

$(function() { 

      $("#query_form").autocomplete({ 
        minLength: 2, 
        source: 'http://127.0.0.1:8000/json_results/', 
        focus: function(event, ui) { 
          $("#query_form").val(ui.item.word); 
          return false; 
        }, 
      select: function(event, ui) { 
        $.get ('http://127.0.0.1:8000/json_detail/', 
           { 
           item: ui.item.pk 
           }, 
           function(data) { 
           $('#query_result').prepend(data); 
           }); 
        $("#query_form").val(ui.item.word); 
        return false; 
      } 
    }) 
    .data("autocomplete")._renderItem = function(ul, item) { 
         var tran = $.each(item.fields.translation, function(i){item.fields.translation[i].fields.word}) 
       return $("<li></li>") 
         .data("item.autocomplete", item) 
         .append("<a>" + item.fields.word + tran + "</a>") 
         .appendTo(ul); 
    }; 
}); 

我總的來說是jQuery和JavaScript的一般noob,所以請原諒格式錯誤。無論如何,這裏的問題是,雖然這實際上提出請求和自動完成功能,但$ .each(item.fields.translation,function(i)item.fields.translation [i] .fields.word})返回自動完成列表中的[object,Object]。如果我通過alert()輸出它,它會返回正確的值。如果我只是使用.append行中的item.fields.translation [0] .fields.word,它會輸出該值。但由於某種原因,當我要求它做我想做的事情時,我得到[object Object] 因此,任何人都知道我做錯了什麼?提前感謝!

回答

1

您正在設置變量tran等於$.each()函數,其中returns jQuery。這就是爲什麼它最終成爲一個對象。

我不清楚你到底在做什麼。您正在循環訪問item.fields.translation數組中的項目,但最終會執行一個附加操作,就像該循環應該只返回一個字符串一樣。但item.fields.translation有其陣列中的兩個項目,所以...你可以建立一個這樣的數組:

var tran = []; 
$.each(item.fields.translation, function(i){ 
    tran.push(item.fields.translation[i].fields.word); 
}); 
//tran now equals ['comprender','entender'] 

不知道有沒有什麼幫助。如果你澄清你期望tran是什麼,那麼我可以進一步幫助。

另外,您可以將當前迭代中的項目值(而不僅僅是索引/鍵)傳遞給$.each()中的函數。例如:

$.each(item.fields.translation, function(i,v){ 
    //the following is the same as tran.push(item.fields.translation[i].fields.word); 
    tran.push(v.fields.word); 
}); 
+0

第一個例子正是我所期待的。我不知道推動什麼(就像我說過的,對js總是不喜歡),所以你,我的朋友,是我的新英雄。謝謝謝謝謝謝!蝙蝠工作:D – Nik