\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
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
default