我有多个select2下拉列表。它们的值从各自的json文件加载。表单加载缓慢。
function mySelect2(file,field) {
$.getJSON(file, function(obj) {
$.each(obj, function(key, value) {
$(field).select2({
data: [
{
id: value,
text: key
}
]
});
});
});
}

<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
mySelect2("../data/contactsourcesources.json",'#source_of_contact');
mySelect2("../data/levelofstudysources.json",'#degree');
//mySelect2("../data/institutionssources.json",'#uni');
//mySelect2("../data/countries.json",'#countryorigin');
mySelect2("../data/degreessources.json",'#course');
});
</script>
</head>
<body >
<section>
<label for="source_of_contact">
Contact Method:
<select class="source_of_contact" id="source_of_contact" name="source_of_contact">
</select>
</label>
<label for="degree" class="lbl-text">Degree Type:<span id="required">*</span>
<select class="degree" id="degree" name="degree">
</select>
</label>
</section>
</body>
</html>
&#13;
Json文件:
{"Caf\u00e9 Connect\n":"7e0a7146","Academic Advising Day\n":"academic_advising_day"}
我想将 Json 和 JavaScript 更改为
{"source_of_contact":{"Caf\u00e9 Connect\n":"7e0a7146","Academic Advising Day\n":"academic_advising_day"}}
function mySelect2(file,field) {
$.getJSON(file, function(obj) {
// obj.field, how do I get value of field? I want to be like this
// obj.source_of_contact
$.each(obj.field, function(key, value) {
$(field).select2({
data: [
{
id: value,
text: key
}
]
});
});
});}
答案 0 :(得分:0)
不要使用CDN,下载并使用js的本地副本。这会增加一点时间,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
第二,为了让它更快地加载数据,不要在文档就绪时调用所有GetJSOn函数,在更改下拉值时一个接一个地调用每个函数。