weixin_33738555 2018-09-02 00:41 采纳率: 0%
浏览 27

JS模块模式中的AJAX

I'm creating an application using Module Pattern in JS. I've create two modules and I have this code:

var dataController = (function () {
    var request = new XMLHttpRequest();

    var getFilmes = function () {
        request.onreadystatechange = function() {
            if(request.readyState === 4) {
                if(request.status === 200) {
                    var obj = JSON.parse(request.responseText);
                    return obj; 
                } else {
                    console.log('An error occurred during your request: ' +  request.status + ' ' + request.statusText);
                } 
            }
        }

        request.open('Get', 'http://localhost:8080/api/filmes/5b8947446f506266bc522f38');
        request.send();
    }

    return {
        filmes: function (){
            return getFilmes();

        }
    };

})();

var controller = (function (dataCtrl) {

    var preencheFilmes = function(){
        var obj = dataCtrl.filmes();
        console.log(obj);

    }

    return {
        init: function(){
            console.log("APP START");
            preencheFilmes();
        }
    };

})(dataController, UIController);


controller.init();

The problem is that I can't get the response from AJAX when I'm calling preencheFIlmes in the "init". But I can get the result in the dataController.

Someone can help me? I'm learning how to work with this pattern.

Thank you so much.

  • 写回答

1条回答 默认 最新

  • weixin_33720186 2018-09-02 02:16
    关注

    Your function getFilmes() is asynchronous and doesn't return anything. A simple solution is to add a callback parameter like this:

    var getFilmes = function(callback) {
        request.onreadystatechange = function() {
            if(request.readyState === 4) {
                if(request.status === 200) {
                    var obj = JSON.parse(request.responseText);
                    callback(obj); // <-- calls the callback function
                } else {
                    ...
                } 
            }
        }
        ...
    }
    

    Then you can pass an anonymous callback function when you want to get the results:

    var preencheFilmes = function(){
        dataCtrl.filmes(function(obj) {
            console.log(obj);
        });
    }
    

    Another option is to use the async/await feature, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    评论

报告相同问题?

悬赏问题

  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?