How to get list of objects by using jQuery.get or post
I am using jQuery.get/post methods in my Struts2 application.
See the following code. This URL return "success" and "error". It will hit a method and return a string (the struts2). I have made JSPs that开发者_开发知识库 contatin these strings in them.
But I want to change this approach. If I have to return a list of objects. What I will do. How a method that return a list of objects will be handeled in jQuery. How JSON will help me? I need a pointer on it.
I hope my point is understood.
jQuery.post("register_user.action" , jQuery("#user_form").serialize(),
function(data){
if (data == "success"){
jQuery("#success").dialog("open");
}else if (data == "error"){
jQuery("#error").dialog("open");
}
});
It's difficult to answer the question "How will JSON help you?" without specific context of what you are doing but I can offer up the generic answer. JSON stands for javascript object notation. It has many uses but relative to your question, it allows you to send a serialized representation of your data from the server down to your client without the "bloat" that comes with XML. Another advantage of using JSON over XML is modern browsers have built in support for it so you don't have to worry about parsing data.
You access the data like properties of a class.
Taking your example, you could return an object (I typically use anonymous objects in scenarios like this) with a single BOOL property called 'success' serialized to JSON. You could then avoid string comparisons in your javascript. In my personal opinion, the code becomes much cleaner.
jQuery.post("register_user.action" , jQuery("#user_form").serialize(),
function(data){
if (data.success){
jQuery("#success").dialog("open");
}else{
jQuery("#error").dialog("open");
}
});
This would be the most basic of examples. JSON becomes much more powerful if you return a serialized list of data from the server to the client. Let's say you send a list of comments in JSON. You could then use jquery templating to bind that list against a template and vuala, you can quickly display that day in your format of choice without manually iterating through all items.
As I mentioned, it's hard to be to specific as I don't know exactly what you are looking to accomplish but I hope this helps.
精彩评论