views:

74

answers:

2

Hi

I want to return some errors to my jquery method. What is happening is I am doing a post(with a type of "json") and if they get errors I want to display the error back to them. I am doing client side validation but some of these are errors that are like server related(ie the database died or something and that update could not happen).

Anyways there could be a few errors and I want to return them all at one go.

So the only way I know really how is to use Json but I now I get the json object I want to get all the fields out of it. I don't want to call it by their name though since I want to use the same methods for all my methods and each one has different names.

So if I could call it by index there would be alot less typing.

Can I do this?

A: 

JSON is nothing more than yet another markup-language to describe complex datastructures. JSON gets parsed into javascript data-structures and can represent objects, arrays or just a string in theoretically unlimited depth.

Without knowing if your JSON structure consists of arrays, objects, or {} constructs it's hard to tell if you can.

However, you could have a look at:

var dataObject = { key1 : "error1",
                   key2: "error2"
                 };

for (var key in dataObject) {
  alert(key + " : " + dataObject[key]);
}
Deliria
You should be very careful when using this method - http://www.cosmocode.de/en/blog/detman/2006-06/27-json-and-for-each-pitfalls
Jonathan Sampson
Yes, I probably should have mentioned the issue when the prototype has been extended. I've been bitten by that in the past.
Deliria
Well I am using json.net library. It turns it into a string.
chobo2
+1  A: 

Since you are using jQuery, you could use $.each to iterate over object properties, for example:

var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(obj, function(key, val) {
      console.log(key,val);
});

For objects jQuery internally executes a for...in statement, which does not iterate over built-in properties, however you can have problems if the Object.prototype is extended since that extended members will be iterated also.

Is not a common practice to extend the Object.prototype, but to avoid problems you can use the hasOwnProperty function to ensure that the property exist directly on the object being iterated:

for ( var key in obj) {
  if (obj.hasOwnProperty(key)) {
      console.log(key,obj[key]);
  }
}
CMS