I am saving a json string to local storage with setItem and get it back with getItem. This works, but when loading the same json string via ajax the object is becoming different.
Here is the original object in google-chrome browserconsole:
collection_parameter: Object
->OFFLINE: Array s
->_byId: Object
->models: Array[500]
..
Here is the stringified json (getItem, setItem) local-storage:
{"OFFLINE":[{ "data_type":"OFFLINE",
"Number":"1",
"val_param_1_2_3":0 },
{..},
{..} ]
}
When I am saving the above json-string in a file e.g. called Test.json and load it via ajax the object is not the same anymore.
Here the ajax call:
$.ajax({ //Laden
url: 'Test.json',
method: 'GET',
dataType: 'json',
success: function(recieved_json_parameters) {
collections_parameter=recieved_json_parameters;
}//end success
});//end ajax
The new object collection_parameter in google-chrome is now:
collection_parameter: Object
->OFFLINE: Array [500]
The additional nodes are missing. What can I do to get the exact same object-type as above??
UPDATE1: This is how I create the original json:
var collections_parameter = { OFFLINE: Backbone.Collection.extend() }
collections_parameter.OFFLINE = new collections_parameter.OFFLINE(json);
In order to store a Backbone Collection, you should save the raw data the collection has, which you can get with toJSON(): (the returned value is an array of objects)
collection.toJSON() /* store the object returned by this function */
(In your case, I think the collection is collection_parameter.OFFLINE)
After retrieving the JSON representing the data, create a new Backbone Collection initialized with it:
collection = new MyCollection(json)
where MyCollection is the subclass of Backbone.Collection you're using, or Backbone.Collection itself, and json is the object you retrieved.
The reason for this is that you need to store the actual data represented by the Collection. The Collection object itself provides you functions for accessing and changing the underlying data, but it's not the data itself, and therefore it should not be serialized and stored. After retrieving the raw data, you create a new Collection that will provide you the various functions for accessing the data.
Related
I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)
I download several entities one ajax-request. Then i add them to stores. I need to commit a changes alike one ajax-request. How properly to do it?
Json structure:
{
entity1: [],
entity2: [],
entyty3: []
}
success: function(responce) {
var data = Ext.decode(response.responseText);
store1.add(data['entity1']);
store2.add(data['entity2']);
store3.add(data['entity3']);
}
Well, you can send it as JSON and that can easily be done as follows:
Ext.Ajax.request({
url: 'YourURL',
jsonData: YourObjectRef, // can be any object / array or JSON string
success: function(response, opts) {
// your code
}
});
And if you want to do it with a store use the type auto for the Modelfield. This type can contain any object.
Check the following references:
ExtJs 4.0.7 Stores
ExtJs 3.4.0 Stores
Kindly check autoSync property to automatically sync the Store with its Proxy after every edit to one of its Records. Defaults to false.
you may use like this. because in extjs4, it's necessary to use the model to create a record
success: function(responce) {
var data = Ext.decode(response.responseText),record;
Ext.each(data,function(entity,index,dataItself){
record = Ext.create('YOURMODEL',entity);
store.add(record);
});
}
Am not able to access my xml file which is inside js folder thru the url function inside collections.How to link to this url to retrieve data?
Once you've setted up the path to your file, you'll have to call fetch on the collection. like so:
var Things = backbone.Collection.extend({ url: "path/to/my/file" });
var things = new Things();
things.fetch().done(function() {
console.log( things.toJSON() );
});
Although, this only works with JSON data format. For XML, you'll need to override collection's parse method to return a javascript object from the XML.
I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.
I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.
Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.
Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?
1/29/2013 UPDATE
Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:
In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.
Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!
BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.
Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)
No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.
Yes there is (I tried it with NodeJS):
JSON Schema defaults
Link updated.
i think...you have to use two way binding with your HTML code...so, once your client side change you will get on your costume js file.
check here for knockout js.
Knock Out JS Link
and on C# code use : $("#urlhidden").val() OR Document.GetElemenyByID("#urlhidden").val().
here you will get array/list or textbox value
Use json with Ko
create new viewmodel for knockout js which you will get the idea about on above link.
and create a json call
like:
self.LoadMAS_Client = function () {
try {
var params = { "clientID": ClientId };
$.ajax({
type: "POST",
url: "http://" + ServerString + "/Services/LogisticsAppSuite-Services-Web-Services-MasClientService.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
// in response u will get the data.and use as per your requirement.
eg. self.SelectedClient(response.your value);
},
error: function (ErrorResponse) {
}
});
}
catch (error) {
}
};
================================New Update ==========================================
i think..one way you can do...get data on xml format at C# code and covert into json string...check below code // To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);