2
\$\begingroup\$

This is the way I handle an Ajax response. I am sure it can be improved.

success: function (json) { 
 $.each(json, function(index,item){ 
 if (item.field == "article_id") {
 $("#article_id").val(item.value);
 } else if (item.field == "naslov") {
 $("#naslov").val(stripslashes(item.value));
 }else if (item.field == "slug_naslov") {
 $("#slug_naslov").val(item.value);
 }else if (item.field == "datum") {
 $("#datum").val(item.value);
 }else if (item.field == "url") {
 $("#url").val(item.value);
 }else if (item.field == "tekst") {
 $("#tekst").val(stripslashes(item.value));
 }else if (item.field == "tag_title") { //handle tags - tokeninput 
 var tagoviArray = item.value; 
 var tagoviInput = $("#txtTags"); 
 $(tagoviInput).tokenInput("clear");
 $.each(tagoviArray, function (index, value) { 
 var arr = value.split(','); 
 $.each(arr, function (i, v) { 
 if (!(v=="")) { 
 $(tagoviInput).tokenInput("add", {id: "", name: v}); tag
 }
 }); 
 });
 }else if (item.field == "love") {
 $("#love").val(item.value);
 } 
 });
 return false;
 }
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 7, 2012 at 10:41
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Maybe something like this?

success: function (json) {
 var decorators = {},
 handlers = {};
 // decorators prepare content for insertion
 decorators.naslov = stripslashes;
 decorators.tekst = stripslashes;
 // specialized handlers
 handlers.tag_title = function (value) {
 // do the tokenization-stuff here
 };
 // Go through the response
 $.each(json, function (index, item) {
 var value = item.value;
 // if the field has its own handler, use that
 if( typeof handlers[item.field] === "function" ) {
 handlers[item.field](value);
 } else {
 // Otherwise, send the value through the decorator
 // (if there is one for the given field), and
 // insert the value in the corresponding input
 if( typeof decorators[item.field] === 'function' ) {
 value = decorators[item.field](value);
 }
 $("#" + item.field).val(value);
 }
 });
}
answered Oct 7, 2012 at 11:42
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.