JSON object:
{"id":75,"year":2011,"make":"Aston Martin","model":"V12 Vanquish"}
jQuery:
function post() {
$("form").on("ajax:success", function(e, data, status, xhr) {
var json = JSON.parse(xhr.responseText);
$.each(json, function(k, v) {
$("#vehicle_record").append('<li class="'+k+'">'+v+'</li>');
});
});
}
HTML page output:
75
2011
Aston Martin
V12 Vanquish
75
2011
Aston Martin
V12 Vanquish
Questions:
- Why is the output rendered twice? (I only expect it once)
- Is there a better way to render JSON to the page? (please advise)
--UPDATE--
The following a walk through of the UX:
FORM ONE: name > click next > post
> FORM TWO > Choose Vehicle > click next > post
> see vehicle picked: add another vehicle? Y (BACK to FORM TWO) / N (continue...)
I need to be able to use post
for each model independently without interference. So how do I get for example all of the JSON objects submitted to the vehicle model? (I need this post function to be modular)
Perhaps I can do something like this?:
function post() {
$("form").on("ajax:success", function(e, data, status, xhr) {
var json = JSON.parse(xhr.responseText);
var model = e.currentTarget.action;
renderOnPage(json, model);
});
}
function renderOnPage(data, model) {
if ( model.match(/vehicles/) ) {
$.each(data, function(k, v) {
$("#vehicle_record").append('<li class="'+k+'">'+v+'</li>');
});
}
}