码迷,mamicode.com
首页 > Web开发 > 详细

【Lua】LWT后台用JSON与 ExtJS传递数据

时间:2014-11-19 23:41:32      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

  要完成目录树的构建,需要前台ExtJS构筑页面,后台处理逻辑,中间由JSON传递数据。

  首先搭建后台环境:

 1 require "httpd" 
 2 require "lfs"
 3 
 4 request, args = ... 
 5 
 6 local s = {root = { 
 7         text = "rootNode",
 8         expanded = true,
 9         children = {
10             {
11                 text = book1,
12                 leaf = true
13             },
14             {
15                 text = "book2",
16                 expanded = true,
17                 children = {
18                     {
19                         text = "con1",
20                         leaf = true
21                     },{
22                         text = "con2",
23                         leaf = true
24                     }
25                 }
26             },
27             {
28                 text = "book3",
29                 expanded = true,
30                 leaf = true
31             }
32         }
33     }
34 }
35 
36 local cjson = require("cjson")
37 local tJson = cjson.encode(s)
38 
39 httpd.set_content_type("text/json")
40 httpd.write(tJson)

  这里虚拟了一个树数据结构s,将其打包后返回给请求方。

  然后是html部分:

 1 <html>
 2     <head>
 3         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 4         
 5         <title>ExtJS TreePanel</title>
 6         <link rel="stylesheet" type="text/css" href="../../ext-5.0.0/examples/shared/example.css" />
 7         
 8         
 9         <script type="text/javascript" src="../ext-5.0.0/examples/shared/include-ext.js"></script>
10         <script type="text/javascript" src="../ext-5.0.0/examples/shared/options-toolbar.js"></script>
11         
12         <script type="text/javascript" src="test.js" charset="utf-8" ></script>
13   
14     </head>
15     <body style=" margin: 0; padding: 0;">
16     </body>
17 </html>

  最后是ExtJS部分:

 1 Ext.require(Ext.tree.Panel)
 2 
 3 Ext.onReady(function(){
 4     Ext.Ajax.request({
 5         url: m.lua,       //后台文件path
 6         method: post,
 7         params: {
 8             action: getDir,
 9         },
10         success: function(response){
11             var text = response.responseText; 
12             var obj = eval(( + text + )); 
13             console.log(obj);             
14         }, 
15         failure: function() {
16             Ext.Msg.alert("失败","失败了");
17         }
18     });
19 });

  其中response内容是这样的:

bubuko.com,布布扣

  所以可以用"response.responseText"来调用响应内容的主体。

  在数据传输流程中,json是以文本,即字符串的形式传递的,而JS操作的是JSON对象,所以,JSON对象和JSON字符串之间的相互转换是关键。

  JSON字符串转换为JSON对象:

    var obj = eval(‘(‘ + str + ‘)‘);

  这样就能获取一个可供使用的JSON对象了。

    bubuko.com,布布扣

【Lua】LWT后台用JSON与 ExtJS传递数据

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/linxiong945/p/4108965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!