I need to make a json string for grid table field list.and need to send them java back end.
I have to send
id,
name,
listOfProjects,
listOfProjects contains following list,this list may contains number of items.
prjId,
prjName
Please tell me how to create a json string ?
I tried with following code sample
var dataStr = new Object();
dataStr.id=myId;
dataStr.name="myName";
dataStr.plist = new Array();
dataStr.plist[0].prjId=1stId;
dataStr.plist[0].prjName="1stName";
dataStr.plist[1].prjId=2ndId;
dataStr.plist[1].prjName="2ndName";
dataStr.plist[2].prjId=3rdId;
dataStr.plist[2].prjName="3rdName";
var data = Ext.JSON.encode(dataStr);
Ext.Ajax.request({
url : '/E2EAT/authentication/userdetails.json',
method : "GET",
headers: {
'Content-Type': 'application/json'
},
params : 'data=' + data ,
useDefaultXhrHeader : false,
withCredentials: true,
});
I can use the code above, but I need to iterate grid
1 . Please let me know how can I iterate a grid with sencha?
2 . What's the best method to make json string and send back end?
Ext gives you two loop functions: Ext.each, and Ext.iterate for objects.
To iterate over columns of a grid, you can use the Ext.grid.Panel#columns array property, containing Columns instances. For example, in order to build a list of visible columns, you can do:
var visibleColumns = [];
Ext.each(grid.columns, function(column) {
// Only columns bound to a field (exludes actions colutions, etc.)
if (!Ext.isEmpty(column.dataIndex)) {
if (column.isVisible()) {
visibleColumns.push({
field: column.dataIndex
,label: column.text
});
}
}
});
A grid doesn't necessarily have a column for every field of the underlying store, and it can have extra columns for custom rendering, actions, numbering, selection, etc. So, you may want to iterate over the fields of the store, instead of the grid columns. In this case, we'd be working we've Ext.data.Field objects:
// Get a ref to the store's model. Stores always have models; even
// if none is specified explicitly, one is created implicitly.
var model = grid.getStore().model;
var fieldNames = [];
Ext.each(model.getFields(), function(field) {
fieldNames.push(field.name);
});
Finally, you turn your data into JSON using Ext.encode. Also, you don't have to build the URL query (params) yourself, which would give more flexibility to other parts of your code that may need to add some params:
Ext.Ajax.request({
...
params: {
data: Ext.encode(rawData)
}
});
For a POST request, you can also use the jsonData property, to save yourself the json encoding:
Ext.Ajax.request({
...
jsonData: {
data: rawData
}
});
In many cases, though, it will be preferable to use a store with an appropriately configured data proxy and writer rather than a direct AJAX request.
Related
I have a Sitesand a Positionscollection. Each time the user selects a new site, the id is sent to the refreshPositions method which is in charge of doing the fetch call.
The route to get the positions look like this '.../sites/1/positions'
view.js
refreshPositions: function(siteId) {
this._positions.fetch({
success: this.onPositionsFetchSuccess.bind(this),
error: this.onPositionsFetchError.bind(this)
});
},
So refreshPositions is called whenever I need to update the positionson the page and the siteId parameter has the id, I just don't know to tell fetch to route to something like .../sites/n/positions where n would be the siteId .
Sorry if I missed relevant informations for my question, I'm pretty new to backbone.
I see, so you are calling fetch from your Positions Collection. The out-of-the-box functionality there is to fetch the whole collection (every Position object) if you have a RESTfull api set up. If you want more specific behaviour from your collection, you can probably write it into the Collection object definition.
var PositionCollection = Backbone.Collection.extend({
initialize: function(models, options) {
this.siteId = (options && options.siteId) || 0;
},
url: function() {
if (!this.siteId) {
return '/positions'; // or whatever
}
return '/sites/' + this.siteId + '/positions';
},
// etc...
});
Then, assuming that _positions refers to an instance of PositionCollection you can do:
refreshPositions: function(siteId) {
this._positions.siteId = siteId; // or wrap in a setter if you prefer
this._positions.fetch({
success: this.onPositionsFetchSuccess.bind(this),
error: this.onPositionsFetchError.bind(this)
});
},
I am trying to use store.loadData(data, true) to append data to an existing store but for some reason it is clearing the store and replacing it with the new data which should only happen if the boolean is set to false which it is not. Is there something I am missing that I need to do to make sure the data is appended to the old data and not replacing it entirely?
Edit Additional code. Currently I am pulling a row from a grid and creating a new window with additional information for that object that is pulled from a database. The idea is that all the possible data for the rows is stored in one store and then when the window appears the store has a filter added so that you only see data that pertains to that particular object. At some point I iterate every single object in the grid and check to see if it has data that was edited. Which is an issue if I only have data from the last object that was edited.
editSelectedNode: function(grid, rowIndex, colIndex){
var store = Ext.getStore('EditStore');
var win = Ext.create('BOMGeneratorSencha.view.EditMenu', {});
var item = grid.getStore().getAt(rowIndex).get('original');
console.debug(item);
win.show();
var el = win.getEl();
store.clearFilter(true);
console.debug(store.getCount());
if(store.getCount() == 0){
el.mask('Loading Values');
console.debug(store.getCount());
Ext.Ajax.request({
url : 'EditPart.jsp',
timeout: 300000,
params : {
item: item
},
success: function (response, opt) {
el.unmask();
var res = Ext.JSON.decode(response.responseText);
if (res.success) {
console.debug(res.results);
store.loadData(res.results,true);
console.debug(store);
}
else {
console.debug("JSON failure");
Ext.Msg.alert('Error', 'Invalid part number');
}
},
failure: function(response,options){
console.debug("major failure");
el.unmask();
Ext.Msg.alert('Error', 'Connection failed<br>' + response.responseText);
}
});
}
}
I have a code that is similat to your one. But when i get response, I dont use
store.loadData(someData)
instead I am using following steps to load data(piece of my code placed here):
success: function(response, opts){
var obj = Ext.decode(response.responseText)
,data = obj.data
,$ = Ext.ComponentQuery;
var store = Ext.create('MyApp.store.SomeStore',{
data : data
});
$.query('SomeGrid')[0].bindStore(store);
$.query('SomeGrid')[0].refresh();
}
I have the following collection:
AisisWriter.Collections.Posts = Backbone.Collection.extend({
model: AisisWriter.Models.Post,
// Build the url based on blog id.
url: function() {
url = '/api/v1/blogs/' + AisisWriter.blog_id + '/posts/'
return url;
}
});
this allows me to do:
var options = { reset: true };
this.writer_posts.fetch(options).then(this.postsRecieved, this.serverError);
this will return me all posts, current six.
I have tired to do:
var options = { reset: true };
this.writer_posts.fetch({id: id}).then(this.postsRecieved, this.serverError);
// id is the id passed into the route, in this case it's #=> {id: 6}
But this still returns me all six posts, I have seen this answer, but I don't think I should have to go through, or extend the model in the middle of code just to append an ID, that and I use the model for the Post, Put and Delete actions while I use the collection for fetching data.
So how do I return one post?
In general, to get some Model from Collection, you should fetch Collection and then get needed model by id, for example:
this.writer_posts.fetch();
And after Collection will be fetched you get method
this.writer_posts.get(id);
Or you can try to fetch a specific Model by passing required id in the fetch method:
this.writer_posts.fetch({
data: {
id: id
}
});
Or something like that.
I have some data that I'm getting from the server that depending on the situation may bring different fields, so what I have is this:
//This is the way i'm attaching the newly created template to the view
//Still no success
function processDataMethod(response){
//some processing here...
var details = Ext.widget('details');
details.config.itemTpl = new Ext.XTemplate(tplFields);
}
Ext.Ajax.request({
url: '...',
...,
success: function (response, request) {
var combinedData = processDataMethod(response);
operation.setResultSet(Ext.create('Ext.data.ResultSet', {
records: combinedData,
total: combinedData.length
}));
operation.setSuccessful();
operation.setCompleted();
if (typeof callback == "function") {
callback.call(scope || that, operation);
currentList.up().push(Ext.widget('details'));
}
}
});
Any help is appreciated, thanks!!
You have to make a distinction between a number of things:
currentList.up() returns a DOM element (Ext.dom.Element). This has no method push().
With Ext.widget('details', config); you can pass a config like {itemTpl: yourTemplate, data: yourData} to create an instance with a custom template and custom data.
To update your component after creation you can always do someWidget.update(data);.
A component can be rendered to an HTML element with the renderTo option.
A component can be appended to existing components in different ways and you can update the whole layout or parts of it in different ways. This is unnecessary if you are rendering to an HTML element.
Does that help you find your problem?
I am currently working on a chat app and am stuck on getting properties out of an array of objects. I first sent an ajax request with json as the datatype. When I check my (data) parameter in my success function in the console it shows an Array called results which has 9 objects each with 4 properties in them. It looks like this, except each has a different id and text etc.
results: Array[10]
0: Object
createdAt: "2013-05-22T00:41:24.394Z"
objectId: "2tzXVBpwQA"
text: "SYSTEM: I'll be back."
updatedAt: "2013-05
I want to just pull out text: for each of the objects, however I have no clue how to do this. I've searched and used many methods like $grep and for statements to get text out to no avail(I am new to programming)
Here is the sample code
function newFetch(newDisplay){
$.ajax({
url: 'https://api.parse.com/1/classes/chats',
data: null,
success: function(data){
/*alert('Load was performed.');*/
var text = $.grep(data, function(e) { return e.text == text});
newFetch(newDisplay(text));
}
,
dataType:"json"
});
};
NewDisplay in the callback is another function that appends the passed parameter to one of my .divs.
This code snippet so far seems to no grab the text but instead returns just [] when I use console. Any help is appreciated!
JSON.prase is your friend
success: function(data){
//...other success code you might want to run..
var newObjArray = {};
for (var i=0; i<data.length; i++) {
newObjArray[i] = JSON.parse(data[i]);
}
}
this should turn each entry in your array to an objects as well.
JSON.Parse on MDN