views:

40

answers:

2

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

+3  A: 

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.

Russ Cam
Hm, that's what I meant. :-) +1
Tomalak
@Tomalak - and I was going to write the code, but now you have, so +1 for you :)
Russ Cam
+2  A: 

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;
}
Tomalak