2016-06-15 184 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){});

希望它能帮助你:)