2016-06-15 249 views
0

我想從具有json數據的文本文件填充我的選擇框。 Json數據被放置在person.txt文件中。如果您有更好的方法從外部文件填充選擇框,您也可以提出建議。我有大量的選擇框被填充。從文本文件填充選擇框

var json = { 
 
    "1": "Accountancy", 
 
    "2": "American Studies", 
 
    "3": "Anatomy & Regenerative Biology", 
 
};
<html> 
 
<head> 
 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script> 
 
    <title>Test</title> 
 
</head> 
 
<body> 
 
    <select class="selectpicker" data-style="btn-inverse" data-width="300px"> 
 
    <script type="text/javascript"> 
 

 
$.getJSON("person.txt", function(json) { 
 
    $.each(json, function(key, value) { 
 
    $('.selectpicker').append('<option value="' + key + '">' + json[key] + '</option>'); 
 
}); 
 
}); 
 

 
    </script> 
 
</body> 
 
</html>

回答

0

你的代碼似乎要被罰款。

只是如果保存JSON數據,讓您的文件,以.json擴展,而不是.TXT

+0

我已經做到了。但這是行不通的' –

+0

它工作,如果我刪除行「$ .getJSON(」person.txt「,函數(json){」並添加外部json文件爲「「 –

+0

這取決於你如何保存你的文件,爲什麼它不起作用?你得到了哪個錯誤? – Ygalbel

0

的$ .getJSON( 「person.json」 功能(JSON){});對待person.json在本地服務器上。這意味着它就像「http://localhost/.../person.json」。所以把這個json文件放在本地機器的IIS上。瀏覽該文件格式的IIS複製該文件的URL格式瀏覽器並使用如下。 $ .getJSON(「http://localhost/MyLocalSite/person.json」,function(json){});

希望它能幫助你:)