关于使用jquery$.ajax读取javascript文件的困惑

The confuse about use jquery $.ajax to read javascript file

本文关键字:文件 javascript 读取 于使用 jquery ajax      更新时间:2023-09-26

假设我有一个配置javascript文件:

window.Config = {};
Config.UI = {
    "Area": {},
    "Layer": {},
    "Sprites": {},
    "Audio": {}
};
Config.UI.Area = {
    "prop": {
        "uuid": {
            "_type": "string",
        },
        "frame": {
            "_type": "rect",
            "_value": {
                "x": "0",
            },
            "_aka": "frame"
        },
        "zIndex": {
            "_type": "string",
        }
    },

然后我想使用$.ajax来读取这个文件:

        $.ajax({
            url:'js/config.js',
            success:function (data, textStatus) {
                console.log(data);
            }
        })

问题是,如何通过使用$.ajax返回数据,在配置中获得一些键的值?

比如UI.area.prop中的"Config.UI"或"uuid"?或者我可以将它们转换为json吗?

与其使用AJAX,为什么不插入一个脚本呢?

var script = $('<script>');
script.attr('type', 'text/javascript');
script.attr('src', 'js/config.js');
script.bind('load', function() {
    // use window.Config
});
script.appendTo('head');

icktoofay有一个很好的建议,jQuery.ajax调用的问题似乎是缺少dataType: 'script'选项,该选项将评估响应,并应为您提供对象访问权限。您可能还需要研究jQuery.getscript()。

我发现将数据作为javascript对象存储在服务器上并使用Ajax读取它们非常有用和强大。这很容易做到。让我给你举一个我写的教育应用程序的例子。

这是一个我将存储在服务器上的目录文件(l1contents.js)示例:

{
     title : "Lesson 1",
     topics : [
         {name : "Topic  1", file : "l1t1data.js" },
         {name : "Topic  2", file : "l1t2data.js" },
     ]
}

这是我用来处理文件的javascript代码:

    $.ajax({
        url : contentsFileName, // would be set to 'l1contents.js'
        dataType : 'text', // yes this is correct, I want jquery to think this is text
        cache : false,
        success: function(data) {
            var contentsObj = eval('(' + data + ')');
            var lessonTitle = contentsObj.title;
            for (var i = 0; i < contentsObj.topics.length; i++) {
                 var topic = contentsObj.topics [i];
                 // process topic.name and topic.file here
            }
        }
    });

显然,这是简化的,但希望你能明白。我只是简单地使用eval来设置对象。请注意,我甚至不需要任何定义contentsObj结构的javascript代码。(当然,我确实有大量的注释来定义我的对象的结构,但它们只是注释,而不是代码。)

如果您的json文件包含json数据,则可以使用parseJSON()、toJSON(()方法。

另一个解决方案是使用eval(),它将json数据转换为javascript对象,这样您就可以通过给定key来轻松地获得值。