I am starting work on a project that is built completely on JSON data. It is returned like this:
{"location":{"id":10,"contactPhone":"8675309","contactName":"bob","name":"bill smith","zipCode":"90210","state":"California","address1":"104 S. Olive","city":"Temecula","country":"USA"},"success":true}
I am comfortable processing data returned in HTML form (usually tables) by traversing the DOM with the .find and other filtering to find success flags. I have no idea how to do this with JSON - I need to filter to the last object "success" and check if it is true or false. With HTML returned data I do it like this:
submitHandler: function(form) {
$.ajax({
//other ajax stuff
success: function(data) {
var answer = $(data).find("td:eq(1)").text();
var message = $(data).find("td:eq(3)").text();
//console.log(data);
if (answer == "True") {
$('#messages').show().html(message);
} else {
$('#messages').show().html('Error logging in: ' + message);
}
}
});
return false;
}
- Even after using this method I don't completely understand what the function(data) means, Ive used data, msg and response without really understanding what the difference between them are.
I am able to post to the webservice and get the returned JSON with this .ajax call
$.fn.serializeObject = function() {....}
submitHandler: function(form){
var wrapper = {};
var location = {};
wrapper.location = $("#newLocation").serializeObject();
$.ajax({
type: $(form).attr('method'),
url: '/web/service/' + 'locationService' + '/' + 'createLocation',
dataType: 'json',
async: false,
data: JSON.stringify(wrapper),
success: function(msg) {
console.log('success' + msg );
//need to traverse to success and if true, do something
},
error: function(msg) {
console.log('failure' + msg );
//need to traverse to success and if false, do something
}
});
return false;
}
- How do you filter to the "success" part in a JSON string (string or object?)
- What are the correct terms for the key/number pairs in the JSON string i.e. "contactPhone":"8675309"?
- How do you then display the data if "success":"true"? I would imagine you just appendTo a table somehow?