2012-04-01 28 views
1

假设我有一个配置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({ 
      url:'js/config.js', 
      success:function (data, textStatus) { 
       console.log(data); 
      } 
     }) 

的问题是如何通过使用数据$ .ajax return在配置中获得某个键的值?

像ui.area.prop中的“Config.UI”或“uuid”还是可以将它们转换为json?

回答

0

我发现它非常实用且功能强大,可以将数据作为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代码。 (当然,我的确有大量的评论来定义我的对象的结构,但它们只是评论,而不是代码。)

5

与其使用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'); 
+0

+1是的,我同意这个答案。不要使用ajax来加载脚本文件。插入脚本标记使其全部自动化。 – jfriend00 2012-04-01 06:03:31

+1

你碰巧知道jQuery中有一个['getScript()'](http://api.jquery.com/jQuery.getScript/)函数吗? – Joseph 2012-04-01 06:08:02

0

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

另一种解决方案是使用eval(),这将json数据转换为javascript对象,因此您可以通过给定键轻松获取值。

1

icktoofay有一个很好的建议,与jQuery.ajax调用的问题看起来是一个缺少dataType: 'script'选项,它将评估响应,并应给你对象访问。你也可以看看jQuery.getscript()