i could not able to parse my nested json data and i tried in many ways but i could not succeed. any help is appreciated.
Here is my json output looks like:
[
{
"task": {
"locator": "FGWESD",
"subtask": [
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
},
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
}
],
"connectTime": "0",
"id": "0"
}
}
]
Here is my model:
Ext.define('MyApp.model.MyModel',{
extend:'Ext.data.Model',
xtype:'myModel',
config:{
fields:[
{name:'number',mapping:'work.number'},
{name:'id',mapping:'work.id'},
{name:'locator',mapping:'task.locator'},
{name:'gate',mapping:'work.gate'}
]
}
});
Here is the store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
config:{
model:'MyApp.model.MyModel',
storeId: 'id_Store',
// added the url dynamically inside the controller
proxy:{
type:'ajax',
reader:
{
type:"json",
rootProperty: 'subtask'
},
method: 'POST',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
}
}
}
});
Here is my controller code :
Ext.define('MyApp.controller.LoginController', {
extend: 'Ext.app.Controller',
requires: ['Ext.data.proxy.Rest'],
config: {
// My code is too long to add here so am adding store loading when user taps login button
},
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
var url = 'http://localhost:8080/apps';
segmentStore.getProxy().setUrl(url.trim());
segmentStore.load({
scope:this,
callback: function(records, operation, success){
if(success){
console.log('records: ',records);
console.log('records: '+records.length); // prints here 1
console.log('locator: '+records[0].getData().locator);
// prints FGWESD
console.log('locator: '+records[0].getData().number);
//prints undefined
//
}
}
}
)
},
});
Can any one please help me out. how can i get Values of number, gate, id and status?
What are the necessary changes have to be made in model, store and controller ?
Please help me out in resolving ? Thanks.
As I wrote in a comment, I don't think you can achieve that without manually parsing the data and loading it to the store. So the getDetails function should look like this:
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
Ext.Ajax.request({
url: 'http://localhost:8080/apps',
success: function(response){
var responseObj = Ext.decode(response.responseText);
var task = responseObj[0].task;
var locator = task.locator;
var subtasks = [];
Ext.each(task.subtask, function(subtask) {
subtasks.push({
number: subtask.work.number,
id: subtask.work.id,
gate: subtask.work.gate,
locator: locator
});
});
segmentStore.setData(subtasks);
}
});
}
Also, when using this method you should remove the mapping from your model, and you can get rid of the proxy definition of the store. Also, I'm not sure why you want to create the store in the "getDetails" and not define it in the 'stores' config of the controller, but maybe you have your reasons..
I didn't run the code, so there maybe errors, but I hope you get the idea.
I think the root property of your store should be:
rootProperty: 'task.subtask'
Related
I'm hoping someone can guide me on how to deal with this json data structure.
Here's an example of that: (I have zero control of this data)
{
"1": {
"name": "thing 01",
"attributes": {
"color": "red",
"brand": "ACME"
}
},
"2": {
"name": "thing 02",
"attributes": {
"color": "blue",
"brand": "ACME"
}
}
}
So I'm confused about how to get the records using the reader
Ext.define('MyApp.model.Thing', {
extend: 'Ext.data.Model'
fields: [
{ name: 'name' },
{ name: 'attributes', type: 'auto' }
],
proxy: {
type: 'rest',
url: 'http://example.com/api/things',
reader: {
type: 'json',
rootProperty: ??? // <--- How should this work?
}
}
});
I've wondered if there's a way to do something like...
rootProperty: '[id]'
Also is there a way to specify the ID when it is the data object? Maybe somehow using the idProperty config on the Model?
Should I use the reader.format method? That would seem a little gross...
Any ideas are apreciated. Thanks!
Write a custom reader class:
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.myreader',
config: {
transform: function (data) {
var ret = [],
key, o;
for (key in data) {
o = data[key];
o.id = key;
ret.push(o);
}
return ret;
}
}
});
Ext.define('Thing', {
extend: 'Ext.data.Model',
fields: ['name', 'attribute'],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'myreader'
}
}
});
Example fiddle.
Your EXACT question is already answered here.
You should implement a custom reader and override the getResponseData method.
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.myreader',
getResponseData: function(response) {
var data = this.callParent([response]);
//do stuff here
return data;
}
});
I have a JSON response that is nested like the following (simplified, but same format):
{
"response":{
"v":"1.0",
"users":[
{
"firstName":"Nicole",
"LastName":"A",
},
{
"firstName":"John",
"LastName":"B",
},
{
"firstName":"Bob",
"LastName":"C",
}
],
}
}
Here is the model:
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
config: {
fields: [
{
name: 'firstName'
},
{
name: 'lastName'
}
]
}
});
I am starting from the sencha architect tutorial for CityBars, so most of the code should be quite basic, and I am just trying to get the users from the json response loaded. Here is the controller:
Ext.define('MyApp.controller.User', {
extend: 'Ext.app.Controller',
launch: function() {
var me = this;
Ext.Viewport.setMasked({ message: 'Loading Attendees...' });
me.getUsers(function (store) {
me.getDataList().setStore(store);
});
},
getUsers: function(callback) {
var store = Ext.data.StoreManager.lookup('UserStore'),
url = 'http://urltogetjsonresponse'
store.getProxy().setUrl(url);
store.load(function() {
callback(store);
});
},
});
Here is the store:
Ext.define('MyApp.store.UserStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.User',
'Ext.data.proxy.JsonP',
'Ext.data.reader.Json'
],
config: {
model: 'MyApp.model.User',
storeId: 'UserStore',
proxy: {
type: 'jsonp',
reader: {
type: 'json',
rootProperty: 'response.user'
}
}
}
});
I tried 'response.user' but it did not work for me. I have already looked all over and know that using rootProperty: 'user' would work, if the users attribute were at the same level as "response" instead of nested under it. I have also tried adding record: 'users' but that did not seem to work either.
If anybody knows if this is doable and has an easy solution to this, that would be great. I don't actually understand how the proxy works, so if anybody can explain a bit about that, it would be helpful too. Thanks.
Taken from Sencha's documentation about the JSON reader :
{
"count": 1,
"ok": true,
"msg": "Users found",
"users": [{
"userId": 123,
"name": "Ed Spencer",
"email": "ed#sencha.com"
}],
"metaData": {
"idProperty": 'userId',
"rootProperty": "users",
"totalProperty": 'count',
"successProperty": 'ok',
"messageProperty": 'msg'
}
}
The rootProperty here is 'users', so you'll need to specify users (which is the name of the array containing your instances of model) and not user .
i want my jqgrid programmatically move next page with reloaded data. for example: every 5 seconds change page and get refreshed data.
---> datatype: 'json' <---
is in loop() function. brings reloaded page, but it does not pass the next page. stuck on the first page. if i delete it goes the next page, but the page doesn't refresh.
i read and tried, tried, tried everything but no luck as of yet. Please help..
<script>
function fill() {
jQuery("#jqGrid").jqGrid({
url: '#Url.Content("~/Handler/GetAjaxGridData")',
datatype: 'json',
height: 'auto',
altRows: true,
loadonce:true,
pager: '#pager',
rowNum: 3,
colNames: ['birim_adi', 'durum'],
colModel: [
{ name: 'cell.birim_adi', index: 'birim_adi' },
{ name: 'cell.durum', index: 'durum' }
],
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.rows; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.rows.length; }
},
loadComplete: function (data) {
var total_pages = $("#sp_1_pager").text(); // total pages
$('#hdn_total_pages').val(total_pages);
},
ajaxGridOptions: { cache: false }
});
}
function loop() {
var i = 1;
setInterval(function () {
var total_pages = $('#hdn_total_pages').val();
$("#jqGrid").setGridParam({
datatype: 'json', // <--When I delete it goes to another page, but the page does not refresh.
page: i,
}).trigger('reloadGrid');
i++;
if (i > total_pages) { i = 1; }
}, 5000);
}
</script>
<script>
$(function () {
fill();
loop();
});
</script>
<table id="jqGrid"></table>
<div id="pager"></div>
<input type="hidden" id="hdn_total_pages" value="1" />
and then my json like this:
{
"total": 1,
"page": 1,
"records": 6,
"rows": [
{
"id": 1,
"cell": {
"birim_adi": "a",
"durum": "test"
}
},
{
"id": 2,
"cell": {
"birim_adi": "b",
"durum": "test1"
}
},
{
"id": 3,
"cell": {
"birim_adi": "c",
"durum": "test3"
}
},
{
"id": 4,
"cell": {
"birim_adi": "d",
"durum": "test4"
}
}
]
}
The jsonReader is returning a hard-coded value of '1' for page. It looks like your data conforms to the structure jqGrid will work with automatically. You might just try deleting the jsonReader section entirely and give it a shot.
If that's not working (or your data has different names than jqGrid is expecting) you will need to look at fixing jsonReader to return proper values.
Take a look at this blog entry about customizing the jsonReader to work with different data formats. It might help you resolve the page getting stuck. (Full disclosure: I'm the author.)
I am trying to get backbone.js to load json.
The json loads but i am not sure how to get the items into my collection.
Or maybe that happens automatically and i just can't trace out. scope issue?
//js code
//model
var Client = Backbone.Model.extend({
defaults: {
name: 'nike',
img: "http://www.rcolepeterson.com/cole.jpg"
},
});
//collection
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.fetch();
},
render: function () {
alert("test" + this.collection.toJSON());
}
});
var myView = new theView();
//json
{
"items": [
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
}
Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json',
parse: function(response){
return response.items;
}
});
Or fix your JSON:
[
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
If you use rest api, try turn off these parameters:
Backbone.emulateHTTP
Backbone.emulateJSON
I have a question.
I need to send a json format to my backend service. It requires something i haven't managed to create. What i am sending with a form is this:
{
"jobs": {
"name": "dsvs",
"jobType": "CUSTOM",
"description": "sdvsdv",
"tasks": "14,15,16"
}
}
but what i need to send is
{
"jobs": {
"name": "dsvs",
"jobType": "CUSTOM",
"description": "sdvsdv",
"tasks": [14,15,16]
}
}
how can i do this?
This is my form handler:
handler: function () {
var form = this.up('form').getForm();
var formData = Ext.encode(form.getValues());
Ext.Ajax.request({
url: ND.url + 'dna/rjs/secure/service/rest/jobs.json',
method: 'POST',
waitTitle: 'Connecting',
waitMsg: 'Sending data...',
jsonData: {
jobs: form.getValues()
}
});
})
I hope anyone has an idea!
You can't by "honest" ways.
You can, however, hack it into that one.
handler: function () {
var form = this.up('form').getForm();
var formData = Ext.encode(form.getValues());
formData.jobs.tasks = formData.jobs.tasks.split(',');
Ext.Ajax.request({
url: ND.url + 'dna/rjs/secure/service/rest/jobs.json',
method: 'POST',
waitTitle: 'Connecting',
waitMsg: 'Sending data...',
jsonData: {
jobs: formData
}
});
})
You don't use your formData in your example, despite having it, BTW.
That would result in:
{
"jobs": {
"name": "dsvs",
"jobType": "CUSTOM",
"description": "sdvsdv",
"tasks": ["14","15","16"]
}
}
If that is still not suitable, than you can further hack it by calling parseInt on each task value.
EDIT:
Added clarification.