3

我想读取 extjs 数据存储的特​​定值并在本地对其进行操作。响应 xml 看起来像:

<user><name>abc</name><surname>def</surname><book><bname>book1</bname></book></user>

当收到响应并且我想读取“bname”值时,我的商店将只有一个用户条目。到目前为止,我已经尝试了两种方法,并且都给出了错误。

方法1:

Ext.define('user', {
     extend: 'Ext.data.Model',
     fields: [ 'name', 'surname'],
     hasMany: {model: 'Book', name: 'book'},
      proxy: {
        type: 'rest',
         url : request,
         reader: { type: 'json', root: 'user'}
     }
 });
 Ext.define('Book', {
     extend: 'Ext.data.Model',
     fields: [ 'name'],
     belongsTo: 'user'
 });
 var userstore = Ext.create('Ext.data.Store', {
        model: "user"
 });
 incidentstore.load({
     callback: function() {
        var inc = userstore.first();
        var bk = inc.getBook();
        console.log(dev.get('bname'));
    }
});

运行上面的代码会给出“Ext.define 不是函数”的错误。

方法2:

var proxy1 = new Jx.JxHttpProxyRest({
    url: request,
    api : {
            read : { headers : {     'Accept' : APP + '.abc.def.usermanage.user+json;version=1' } }
        }
    });

var reader = new Ext.data.XmlReader( {
    rootProperty : 'user',
    record : 'book',
    id : 'id',
}, [{ name : 'bname', mapping : 'book > bname'} ]);

var writer = new Ext.data.XmlWriter( {
    encode : false
});

var newstore = new Ext.data.Store( {
    id : 'book',
    restful : true,
    proxy : proxy1,
    remoteSort : true,
    reader : reader,
    writer : writer,
    autoload: true,
    listeners: {
        load: function() {
            console.log(newstore.data.first());
        }
    }
});
Ext.data.DataProxy.addListener('load', function(proxy, type, action, options, res) {
    console.log(res.responseText);
});
newstore.load( {
    params : { start : 0, limit : myPageSize },

});

上面的代码不会在控制台上显示任何内容。

我是 extjs 的新手,不知道如何从响应中访问“bname”值。如果有人可以提供帮助,那就太好了

4

5 回答 5

5

看看这个:

// The user model definition
Ext.define('user', {
   extend: 'Ext.data.Model',
   fields: [ 'name', 'surname', 'book' ]
});

// The store instance
var userstore = Ext.create('Ext.data.Store', {
   model: 'user',
   proxy: {
        type: 'memory',
        reader: {
            type: 'xml',
            record: 'user',
            root: 'users'
        }
    }
});

// data sample to test the approach
mydata =
    [
        ['Juan', 'Alonso', [ { bname: 'El loco' }, { bname: 'El cuerdo' } ]],
        ['Susana', 'Cabrera', [ { bname: 'Adios a las palomas' }]]
    ];

// load the store with the sample data 
userstore.loadData(mydata, false);  

// display the first book for the first record
var firstRecord = userstore.getAt(0);
var firstBook = firstRecord.get('book')[0]; 
alert(firstBook.bname )

或在这里查看工作代码:http: //jsfiddle.net/lontivero/HTj5Q/

如您所见,它工作正常。但是,如果您的商店“总是”只有一条记录,那么您不应该使用商店,您应该使用模型并加载模型。

更新

好的,如果您使用的是 extjs 3.1.1(之前最好提供如此重要的信息),您可以按照以下方式进行操作:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
      <title>For extjs 3.1.1</title>

        <script src="http://extjs-public.googlecode.com/svn/tags/extjs-3.1.1/release/adapter/ext/ext-base.js" type="text/javascript" ></script>
        <script src="http://extjs-public.googlecode.com/svn/tags/extjs-3.1.1/release/ext-all.js" type="text/javascript" ></script>
    </head>
    <body>
        <script type="text/javascript">
        Ext.onReady(function(){
            // The store instance
            var userstore = new Ext.data.ArrayStore({
                 fields: ['name', 'surname', 'book'],
                 reader: new Ext.data.ArrayReader({
                     idIndex: 0  // id for each record will be the first element
                 })
            });

            // data sample to test the approach
            mydata =
                 [
                      ['Juan', 'Alonso', [ { bname: 'El loco' }, { bname: 'El cuerdo' } ]],
                      ['Susana', 'Cabrera', [ { bname: 'Adios a las palomas' }]]
                 ];

            // load the store with the sample data 
            userstore.loadData(mydata, false);  

            // display the first book for the first record
            var firstRecord = userstore.getAt(0);
            var firstBook = firstRecord.get('book')[0]; 
            alert(firstBook.bname );
        });

        </script>
    </body>
</html>
于 2012-12-06T00:21:28.397 回答
2

下面的代码对我有用:

var newproxy = new Ext4.data.proxy.Rest({
    url : request,
    headers : {
        },
    reader :  {
        type : 'json',
        root : 'user.book'
    }});

 // Typical Store collecting the Proxy, Reader and Writer together.
 var newstore = Ext4.create('Ext4.data.Store', {
     id : 'book',
     fields: ['bname'],
     restful : true, // <-- This Store is RESTful
     autoLoad : true,
     proxy : newproxy
 });

var book;
newstore.load();
newstore.each(function(rec) {
    book= rec.get('bname');
});
于 2012-12-13T20:31:54.583 回答
1

您使用的是 Ext 版本 4 代码,但您的库是 3.1.1

除非您将库升级到版本 4,否则它根本行不通。

于 2012-12-07T00:00:19.617 回答
0

为了使 Lontivero 的示例完整,使用 findRecord 方法查找特定键上的记录也很有用。如下示例所示(基于 lontivero 的示例),它只会获取第一个找到的记录。因此,如果您使用具有唯一键的商店,这将非常有用。

您可以在以下位置查看此示例:http: //jsfiddle.net/jvandemerwe/dGUGb/25/

// The user model definition
Ext.define('user', {
   extend: 'Ext.data.Model',
   fields: [ 'name', 'surname', 'book' ]
});

// The store instance
var userstore = Ext.create('Ext.data.Store', {
   model: 'user',
   proxy: {
        type: 'memory',
        reader: {
            type: 'xml',
            record: 'user',
            root: 'users'
        }
    }
}); 

// data sample to test the approach
mydata =
    [
        ['Juan', 'Alonso', [ { bname: 'El loco' }, { bname: 'El cuerdo' } ]], 
        ['Juan', 'Lopez', [ { bname: 'Superdooper' }, { bname: 'Swinglist' } ]],  
        ['Susana', 'Cabrera', [ { bname: 'Adios a las palomas' }]]
    ];

// load the store with the sample data 
userstore.loadData(mydata, false);  

// Finds the first!!! matching Record in this store by a specific field value.
// API info: findRecord( fieldName, value, [startIndex], [anyMatch], [caseSensitive], [exactMatch] )

var keyToFind = 'Juan';
var found = userstore.findRecord('name', keyToFind, 0, false, false, true);

if (found != null) {

    var list = '';
    var author = found.get('name')+' '+ found.get('surname');
    var books = found.get('book');

    Ext.each(books, function(book, idx) {
        if (list != '') list = list + ', ';
        list = list+book.bname;
    });

    alert('Books of '+author+'\n'+list);
} else {
    alert('no books with key \''+keyToFind+'\'');
}
于 2012-12-06T22:29:45.030 回答
0
var departmentStore = Ext.create('Ext.data.Store', {
fields : [
'name',
'active',
'dateActive',
'dateInactive',
'description',
'director',
'numEmployees',
{
name : 'id',
type : 'int'
}
],
proxy : {
type : 'ajax',
url : 'data.json',
reader : {
type : 'json',
root : 'data',
idProperty : 'id',
//successProperty : 'meta.success'  //???
}
}
});

departmentStore.load({
callback : function(records, operation, successful) {
if (successful) {
console.log('department name:',
records[0].get('name'));
}
else {
console.log('the server reported an error');
}
}
});
于 2015-01-16T12:46:14.223 回答