【问题标题】:How to use requiereJS to import local imput json file?如何使用 requireJS 导入本地输入的 json 文件?
【发布时间】:2019-05-29 12:19:58
【问题描述】:

我想将本地输入文件中的 json 加载到我的 js 脚本中。

json 被导入,我可以得到文件对象,但是我无法正确获取 JSON 并将其解析为 JS 对象

我尝试使用 RequiereJS,这似乎是最好和最快的解决方案,但我无法使这条线工作

require(['json!someFile.json'], function(data){

})

这是我在 HTML 中的输入:

<input type="file" class="custom-file-input" onchange="loadFile(this.file) accept="application/json">

这里是我的 js 文件:

function loadFile(file) {
    var myJson;
    var url = URL.createObjectURL(file);
    require(['json!'+url+''], function(data){
        myJson = data;
    }
}

或者这个:

require(['json!'+file+''], function(data){

【问题讨论】:

    标签: javascript json file input


    【解决方案1】:

    你可以使用 jQuery 的 ajax 函数

    $.ajax({
        type: "Get",
        url: "data.json",
        dataType: "json",
        success: function(data) {
    
        },
        error: function(){
            alert("json not found");
        }
    });
    

    注意:您需要将文件保存在服务器中,然后才能正常工作。

    【讨论】:

      猜你喜欢
      • 2020-01-09
      • 2013-06-17
      • 2015-11-15
      • 2021-07-24
      • 2022-12-05
      • 2014-02-09
      相关资源
      最近更新 更多