`
easonfans
  • 浏览: 251735 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

怎样获得JSON语句中的属性值

阅读更多

How to read property's value in JSON --怎样获得JSON语句中的属性值

来源:http://extjs.com/forum/showthread.php?t=15875

paging.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  
<title>Paging Grid Example</title>  
  
<link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />  
  
    <!-- GC -->  
        <!-- LIBS -->  
        <script type="text/javascript" src="../../adapter/ext/ext-base.js"></script>  
    <script type="text/javascript" src="../../ext-all-debug.js"></script>  
        <!-- ENDLIBS -->  
  
    <script type="text/javascript" src="../../ext-all.js"></script>  
       
<script type="text/javascript" src="paging.js"></script>  
<link rel="stylesheet" type="text/css" href="grid-examples.css" />  
  
<!-- Common Styles for the examples -->  
<link rel="stylesheet" type="text/css" href="../examples.css" />  
</head>  
<body>  
<script type="text/javascript" src="../examples.js"></script><!-- EXAMPLES -->  
<h1>Paging Grid Example</h1>  
<p>This example shows how to create a grid with paging. This grid uses a ScriptTagProxy to fetch cross-domain   
    remote data (from the Ext forums).</p>  
<p>Note that the jsis not minified so it is readable. See <a href="paging.js">paging.js</a>.</p>  
<!--    <a href="#" onclick="Ext.log('Hello from the Ext console.');return false;"><img src="inspector.gif" width="600" height="337" style="margin:15px;"/></a>  
-->  
<div id="topic-grid"></div>  
  
</body>  
</html>  

paging.js:

Ext.onReady(function(){   
  
    // create the Data Store   
    var ds = new Ext.data.Store({   
        // load using script tags for cross domain, if the data in on the same domain as   
        // this page, an HttpProxy would be better   
        proxy: new Ext.data.HttpProxy({   
            url: 'a.jsp'//'http://extjs.com/forum/topics-browse-remote.php'   
        }),   
  
        // create reader that reads the Topic records   
        reader: new Ext.data.JsonReader({   
            root: 'topics',   
            totalProperty: 'totalCount',   
            id: 'threadid'   
        }, [   
            'title', 'forumtitle', 'forumid', 'author',   
            {name: 'replycount', type: 'int'},   
            {name: 'lastpost', mapping: 'lastpost', type: 'date', dateFormat: 'timestamp'},   
            'lastposter', 'excerpt'   
        ]),   
  
        // turn on remote sorting   
        remoteSort: true   
    });   
    ds.setDefaultSort('lastpost', 'desc');   
  
    // pluggable renders   
    function renderTopic(value, p, record){   
        return String.format(   
                '<b><a href="http://extjs.com/forum/showthread.php?t={2}" target="_blank">{0}</a></b><a href="http://extjs.com/forum/forumdisplay.php?f={3}" target="_blank">{1} Forum</a>',   
                value, record.data.forumtitle, record.id, record.data.forumid);   
    }   
    function renderLast(value, p, r){   
        return String.format('{0}   
by {1}', value.dateFormat('M j, Y, g:i a'), r.data['lastposter']);   
    }   
  
    // the column model has information about grid columns   
    // dataIndex maps the column to the specific data field in   
    // the data store   
    var cm = new Ext.grid.ColumnModel([{   
           id: 'topic', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })   
           header: "Topic",   
           dataIndex: 'title',   
           width: 420,   
           renderer: renderTopic   
        },{   
           header: "Author",   
           dataIndex: 'author',   
           width: 100,   
           hidden: true   
        },{   
           header: "Replies",   
           dataIndex: 'replycount',   
           width: 70,   
           align: 'right'   
        },{   
           id: 'last',   
           header: "Last Post",   
           dataIndex: 'lastpost',   
           width: 150,   
           renderer: renderLast   
        }]);   
  
    // by default columns are sortable   
    cm.defaultSortable = true;   
  
    var grid = new Ext.grid.GridPanel({   
        el:'topic-grid',   
        width:700,   
        height:500,   
        title:'ExtJS.com - Browse Forums',   
        store: ds,   
        cm: cm,   
        trackMouseOver:false,   
        sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),   
        loadMask: true,   
        viewConfig: {   
            forceFit:true,   
            enableRowBody:true,   
            showPreview:true,   
            getRowClass : function(record, rowIndex, p, ds){   
                if(this.showPreview){   
                    p.body = '<p>'+record.data.excerpt+'</p>';   
                    return 'x-grid3-row-expanded';   
                }   
                return 'x-grid3-row-collapsed';   
            }   
        },   
        bbar: new Ext.PagingToolbar({   
            pageSize: 25,   
            store: ds,   
            displayInfo: true,   
            displayMsg: 'Displaying topics {0} - {1} of {2}',   
            emptyMsg: "No topics to display",   
            items:[   
                '-', {   
                pressed: true,   
                enableToggle:true,   
                text: 'Show Preview',   
                cls: 'x-btn-text-icon details',   
                toggleHandler: toggleDetails   
            }]   
        })   
    });   
  
    // render it   
    grid.render();   
  
    // trigger the data store load   
    ds.load({params:{start:0, limit:25, forumId: 4}});   
  
    function toggleDetails(btn, pressed){   
        var view = grid.getView();   
        view.showPreview = pressed;   
        view.refresh();   
    }   
});

a.jsp:

<%@page contentType="text/html; charset=UTF-8"%>   
<%@page import="org.json.simple.*"%>   
<%   
  JSONObject obj = new JSONObject();   
  JSONArray array = new JSONArray();   
  JSONObject sub = new JSONObject();   
  sub.put("threadid", new Integer(12313));   
  sub.put("forumid", new Integer(32132));   
  sub.put("forumtitle", "help");   
  sub.put("title", "EditorGrid saving data in FF, but not IE (no errors, hard to debug)");   
  sub.put("author", "stevefink");   
  sub.put("lastposter", "stevefink");   
  sub.put("lastpost", new Integer(1192160261));   
  sub.put("excerpt", "Hi all");   
  sub.put("replycount", new Integer(0));   
  array.add(sub);   
  JSONObject sub2 = new JSONObject();   
  sub2.put("threadid", new Integer(12314));   
  sub2.put("forumid", new Integer(32132));   
  sub2.put("forumtitle", "help");   
  sub2.put("title", "EditorGrid saving data in FF, but not IE (no errors, hard to debug)");   
  sub2.put("author", "stevefink");   
  sub2.put("lastposter", "stevefink");   
  sub2.put("lastpost", new Integer(1192160261));   
  sub2.put("excerpt", "Hi all");   
  sub2.put("replycount", new Integer(0));   
  array.add(sub2);   
  obj.put("topics", array);   
  obj.put("status", new Integer(1));   
  obj.put("totalCount", new Integer(111));   
  out.print(obj);   
%>

a.jsp's return value:

{"totalCount":111,"status":1,"topics":[{"forumid":32132,"title":"EditorGrid saving data in FF, but not IE (no errors, hard to debug)","replycount":0,"lastposter":"stevefink","excerpt":"Hi all","forumtitle":"help","threadid":12313,"lastpost":1192160261,"author":"stevefink"},{"forumid":32132,"title":"EditorGrid saving data in FF, but not IE (no errors, hard to debug)","replycount":0,"lastposter":"stevefink","excerpt":"Hi all","forumtitle":"help","threadid":12314,"lastpost":1192160261,"author":"stevefink"}]} 
源码如上:
原文中要获得JSON语句中的‘status’的属性值。在那篇文章的讨论中,有两种方法可以解决这个问题。在我的上一篇日志()中提到了一种方法,但是实际在解决中并不能运行,常报错:“是未定义或者空对象”之所以出现这种情况是因为数据还没有加载那(ds的load函数并没有立刻执行,而是在render()函数执行之后,延迟加载),这个问题有两种解法:
一:另外举个数据。
相应的store编码:
        reader: new Ext.data.JsonReader({

            
root'topics',

            
successProperty'success',  //add this

            
totalProperty'totalCount',

            
id'threadid'

        
}, [

            
'title''forumtitle''forumid''author',

            {
name'replycount'type'int'},

            {
name'lastpost'mapping'lastpost'type'date'dateFormat'timestamp'},

            
'lastposter''excerpt'

        
]), 
相应的json语句:
{"message":"something wrong","totalCount":11,"success":false

对应的访问方法:
ds.load(

    {
params:{start:0limit:25forumId4}},

    {
callback:function(storeoptionssuccess){

    if(
success){

       
alert("success");

       
//Do something here, like grid.render();  

       
return;

    }

    else{

       
alert(store.reader.jsonData.message);

    }

  }

});
另外一种解决方法:
ds.on('load', function(store, records, options) {
    if(!store.reader.jsonData.success) {
        ds.removeAll();
        Ext.Msg.alert('Status', store.reader.jsonData.message);
    }
});
 

这样子就行了!!!

感谢那个外国帖子!


分享到:
评论

相关推荐

    javascript json对象数组排序

    只要数组中的对象存在多个属性,即可传入sql语句排序形式的参数,加以排序,如传入'col1 desc,col2 asc' 就可以实现对数组中对象通过col1倒序排列,如果col1值相同,则通过col2排序,以此类推,列数不受限制.

    Javascript笔记一 js以及json基础使用说明.docx

    定义式的函数语句会优先执行,而变量式的函数语句会在执行其他语句代码之前执行。 在JavaScript中,函数的类型是函数,而不是object。typeof(null)返回object,但null并非object。这点需要特别注意,以免和Number、...

    supersequel:MySQL并行请求API,使用由车把模板构建的简单SQL语句,并由json模式验证

    supersequel是一种无逻辑SQL paralell请求api,使用由车把模板构建的普通SQL语句,并已通过json模式验证。 受GraphQL启发,supersequel可以将多个资源请求和变异包装到一个api调用中。 从而减少SPA的闲聊程度。 与...

    Django ORM 查询表中某列字段值的方法

    在MVC/MVT设计模式中的Model模块中都包括ORM 2.ORM优势 (1)只需要面向对象编程, 不需要面向数据库编写代码. 对数据库的操作都转化成对类属性和方法的操作. 不用编写各种数据库的sql语句. (2)实现了数据模型与...

    ajaxfileupload.js

    success: function (data, status) //相当于java中try语句块的用法 { //data是从服务器返回来的值 alert("cg"); }, error: function (data, status, e) //相当于java中catch语句块的用法 { alert...

    基于SSM框架+Mysql的企业CRM客户关系管理系统项目源码+数据库+项目说明.zip

    项目视频上有错误,查询市场活动的sql语句中的limit后面应该用${beginNo},${pageSize},而不是#{}.此外limit的起始索引应该为0,而不是1 2. vue中调用钩子函数beforeMount(),在页面渲染之前向服务器发送axios...

    序列化Hashtable

    在序列化过程中临时生成的文件中可以发现如下的语句: WriteStartElement(@&quot;ArrayOfAnyType&quot;, @&quot;&quot;); for (int ia = 0; ia ; ia++) { Write1_Object(@&quot;anyType&quot;, @&quot;&quot;, (...

    容灾项目从入门到实战视频.zip

    23-解决列表页面中的json引用对象的问题-1 24-回显和更新的功能-1 25-独立开发的功能说明-1 26-补充-关于hibernate中一对一唯一主键关联的补充-1 27-vue的路由-1 28-shiro介绍和quickstart样例项目-1 29-quickstart...

    精通JS脚本之ExtJS框架.part2.rar

    《精通JS脚本之ExtJS框架》由浅入深地讲解了ExtJS在Web开发中的相关技术。本书共分17章,分别介绍了JavaScript的对象编程、JavaScript浏览器对象模型和事件机制、ExtJS的核心类库和组件、ExtJS的事件处理方式、设计...

    精通JS脚本之ExtJS框架.part1.rar

    《精通JS脚本之ExtJS框架》由浅入深地讲解了ExtJS在Web开发中的相关技术。本书共分17章,分别介绍了JavaScript的对象编程、JavaScript浏览器对象模型和事件机制、ExtJS的核心类库和组件、ExtJS的事件处理方式、设计...

    JavaScript完全自学宝典 源代码

    8.4.html 获取location对象的属性值并刷新页面。 8.5.html 包含链接的文档。 8.6.html 包含链接的文档打开的目标文档。 8.7.html 清空文档的内容。 8.8.html 是否调用close()方法的区别。 8.9....

    JavaScript实战

    2.5.5 修改变量中的值 27 2.6 教程:使用变量创建消息 28 2.7 教程:请求信息 30 2.8 数组 32 2.8.1 创建数组 32 2.8.2 访问数组中的项目 34 2.8.3 向数组添加项目 35 2.8.4 从数组删除项目 37 2.8.5 使用splice( )...

    Windows 批处理调试器3.0

    .bdc文件是JSON文本格式,可以用任何一个文本阅读器打开,不过推荐你在Windows批处理调试器中编辑,以免出错。 添加批处理文件 通过打开文件按钮或者拖拽方式打开批处理文件,就可以把批处理文件添加到当前工程。...

    jquery-1.1.3 效率提高800%

    如果键对应的值是数组,jQuery会将其值赋给同一个键属性。 例如 {foo:["bar1", "bar2"]} 变为 '&foo=bar1&foo=bar2'。 dataType( Intelligent Guess (xml or html)) 数据类型: String 期待由服务器返回值...

    JavaScript详解(第2版)

     5.3 数字、字符串还是布尔值?数据类型转换   5.3.1 parseInt()函数   5.3.2 parseFloat()函数   5.3.3 eval&#40;&#41;函数   5.4 特殊运算符   5.5 应知应会   练习   第6章 条件选择   ...

    乐优商城.xmind

    name 命名为aa,然后sql语句....where s_name= #{aa} 中就可以根据aa得到参数值 修改 回显 Controller @PathVariable("bid") 通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中...

    ExtAspNet v2.2.1 (2009-4-1) 值得一看

    -Button的Pressed属性值能够正确的反映客户端的变化。 -优化Tree控件的AJAX实现。 +为页面的Form添加autocomplete="off"属性。 -参考http://www.cnblogs.com/sanshi/archive/2009/09/04/1560146.html#1635830 ...

Global site tag (gtag.js) - Google Analytics