JavaScript中的require()函数问题

时间:2019-05-09 09:26:57

标签: javascript json requirejs

我正在尝试实现以下代码,在其中尝试读取JavaScript中的json文件。我有两个文件,一个是main.html,它具有主要的javascript代码,称为main.js,另一个是importing.js

这是main.html文件

<!Doctype html>
<html>
    <head>

        Dwell time for workers

    </head>
    <script src = https://requirejs.org/docs/release/2.3.6/r.js></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script type="text/javascript" src="text.json"></script>
    <script src="testing_file.js"></script>
    <script type = "text/javascript"></script>
    <script>
    var Import = new import_file('osama'); // constructor 
    var out = Import.dwell_times()
    console.log('out')
    console.log(out[2]);
</script> 

<body>
    <h1> worker time : </h1>

</body>


</html>

这是imported.js文件

var that = null;

class import_file
{
    constructor(title)
    {
        this.title = title;
        that = this;
    }
    dwell_times()
    {
        console.log('osama')
        var x = [5,4,3,2,1] ; 
        var y = x.toString();
        console.log(y)
        let parsed = require('./updated.json')
        console.log(parsed) ;// Arham
        return parsed;
    }

}
var Import = new import_file('osama'); // constructor 
var out = Import.dwell_times()
console.log('out')
console.log(out[2])

我遇到以下错误

Uncaught Error: Module name "updated.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
    at makeError (r.js:417)
    at Object.localRequire [as require] (r.js:1685)
    at requirejs (r.js:2046)
    at import_file.dwell_times (testing_file.js:16)
    at imported.js:23

我该如何解决此错误?

1 个答案:

答案 0 :(得分:0)

Require无法解析它并自动将其转换。解决方案是转换为回调语法:

var moduleName = './updated.json';
require([moduleName], function(fooModule){
     // do something
})