在准备好文档后,我想使用多个JS文件检索数据:
A.js
var dataController;
let loadedData_haz;
$(document).ready(function () {
dataController = new DataController();
loadedData_A = dataController.getloadedLanguage().A;
fillForm_A(loadedData_haz);
});
B.js
var dataController;
let loadedData_B;
$(document).ready(function () {
dataController = new DataController();
loadedData_B = dataController.getloadedLanguage().B;
fillForm_B(loadedData_B);
});
C.js
var dataController;
let loadedData_C;
$(document).ready(function () {
dataController = new DataController();
loadedData_C = dataController.getloadedLanguage().C;
fillForm_C(loadedData_haz);
});
在我的data.controller.js文件中,我收到了上述文件的JSON对象和数据,例如...
data.controller.js
let dataService;
$(document).ready(function () {
dataService = new DataService();
loadLanguage();
});
function DataController() {
if(!dataService) {
dataService = new DataService();
}
/*
getter
*/
this.getloadedLanguage = function () {
return dataService.getloadedLanguage();
};
}
let loadLanguage = function () {
var m = dataService.loadLanguagePromise();
$.when(m).done(dataService.handleData);
};
在data.service.js中,我读取了TXT.file的内容
data.service.js
letloadLanguage;
function DataService() {
/*
getter
*/
this.getloadedLanguage = function () {
return loadedLanguage;
};
}
DataService.prototype.handleData = function (response) {
loadedLanguage = JSON.parse(response);
localStorage.setItem('lang', response);
};
DataService.prototype.loadLanguagePromise = function () {
return new Promise(function (resolve, reject) {
$.ajax({
url: "php/services/readLanguage.php",
type: "GET",
async: true,
dataTyp: 'json',
success: function (data) {
resolve(data);
},
error: function (xhr, desc, err) {
reject(Error("It broke"));
}
})
})
};
每次我重新加载我的应用程序时,loadedData都是未定义的。有时,loadedData_B是未定义的,有时,loadedData_B和loadedData_C是未定义的。由于我的代码,这很正常。
因此,我想使用 new Promise 将data.service.js中的loadLanguage方法更改为回调函数。我认为这是正确的方法。任何改进或建议都非常欢迎!