2012-11-22 21 views
2

我想請求一些幫助。 我有一個外部JSON文件與內部數組看起來像這樣:在JavaScript中讀取外部JSON文件以填充選擇下拉列表

{ "Files": [ 
    { 
     "fileName": "Trains", 
     "fileID": "t1" 
    }, 
    { 
     "fileName": "Planes", 
     "fileID": "p1" 
    }, 
    { 
     "fileName": "Cars", 
     "fileID": "c1" 
    } 
]} 

我試圖用這個數據最終以填補一個下拉選擇菜單中的XHTML頁面,同時使用JavaScript來寫。 到目前爲止,我已經得到了以下內容,但現在無法弄清楚我最後一個障礙出錯的地方。關於我不理解的任何指針表示讚賞,謝謝。

function fileDropdown() { 
    var options = ""; 
    $.getJSON(
     "json/files.json", 
     function(result) { 
      //find the array and do seomthing 
      $.each(result.Files, function(key, val) { 
       options += '<option value="' + val.fileID + '">' + val.fileName + '</option>'; 
      }); 
     } 
    ); 
    document.write("<select>"+options+"</select>"); 
} 
+0

檢查控制檯在瀏覽器(通常爲F12),並檢查來自AJAX調用產生的任何錯誤。 –

+0

做一個'console.log(val)'來檢查它的結構,我想你是以錯誤的方式訪問它的。 – Naryl

回答

1

謝謝,解決現在的問題。會upvote你,但需要更多的聲譽。

我用

$.each(result.Files, function(file) { 
     selectElement.append($('<option value="' + this.fileID + '">' + this.fileName + '</option>')); 
0

$.getJSON("json/files.json", ...)的意思是 「拿window.location,追加json/files.json然後發送這個URL GET請求」。

要解決此問題,您可以使用絕對file: URL。但是出於安全原因,您的瀏覽器可能會拒絕加載該文件。

另一種方法是讓您的Web服務器在請求上述URL時將文件發送到瀏覽器。

+0

好的,謝謝你的信息 – neilfoxholes

1

試試這個:

function fileDropdown() 
{ 

$.getJSON("json/files.json", function(result) { 
//find the array and do seomthing 
    var options = ""; 
    $.each(result.Files, function(key, val) { 
     options += '<option value="' + val.fileID + '">' + val.fileName + '</option>'; 
    }); 
    var select = $('<select/>'); 
    select.append(options); 
    $(document.body).append(select); 
}); 
} 
+0

我似乎無法得到這種方法工作,謝謝 – neilfoxholes

相關問題