Reputation: 55615
I am making a web service call and receiving a JSON formatted response. After I receive the response, I would like to display the data in a page. Before I display this data on the page I need to perform checks to make sure that certain elements are defined, and if not give them default values (example below).
var scoreSummary = JSON.parse(response).summary;
var gameStatus = scoreSummary.gameStatus ? scoreSummary.gameStatus : 'pre';
var homeRanking = scoreSummary.homeRank ? scoreSummary.homeRank : '';
var awayRanking = scoreSummary.awayRank ? scoreSummary.awayRank : ''
Now I have several pages where I can call this same web service and I do not want to duplicate all the checks, and setting of default values. Is there a way that I can centralize these checks so that I only have them in one place instead of scattered throughout several pages that each make the same service call?
Thanks
Upvotes: 0
Views: 1153
Reputation: 338326
Like, a function call?
function setDefaultValues(jsonResponse) {
var scoreSummary = JSON.parse(jsonResponse).summary;
scoreSummary.gameStatus = scoreSummary.gameStatus || 'pre';
scoreSummary.homeRank = scoreSummary.homeRank || '';
scoreSummary.awayRank = scoreSummary.awayRank || '';
return scoreSummary;
}
Upvotes: 4
Reputation: 125528
Put the check inside a function in an external .js file and link that script file on the pages that make the Web Service call.
On a successful AJAX response, call the function passing in the responseText (or a JavaScript object parsed from the response), perform the validation, and return the response with defaulted values back to the calling code.
Upvotes: 4