Jquery Ajax and Json : How to check if undefined-Collection of common programming errors
I got this Jquery code :
$.ajax({
url: "?module=gestionApplication&action=getTests&scenario="+encodeURI(scenario)+"&application="+$application,
dataType:'json',
success: function( data ) {
$.each(data, function(i, item) {
$("#tests tbody").append($tr+"
"+item.ID+"
" + "
"+ "Header : "+item.HEADER + '
' + "Méthode : "+item.METHODE + '
' + "PostBody : "+item.POSTBODY + '
' + "URL : "+item.URL + '
' + "ParseReponse : "+item.PARSEREPONSE + '
' + "
" +
So i got a JSON response from my server, but not all fields are full. Sometimes item.HEADER or item.METHODE can not be defined, so I get “undefined” text in my table. Problem is, I’m French and I would like different text and not this ‘undefined’.
So how can I test if the variable is defined or not? Or even better, is it possible to change this ‘undefined’ text to different text in case the variable is not defined?
-
You can do a quick conditional / logical-OR check within your concat:
"Header : " + (item.HEADER || '') + '
' +so now, if
item.HEADER
isundefined
we will encounter the empty string instead. Of course you could also use a more expressive string like"empty"
or whatnot. -
if (typeof variable == "undefined") { // variable is undefined }
-
Use a ternary operator… ( test ? do if true : do if false )
...+( item.HEADER ? item.HEADER : "something french" )+...
-
easily done like so:
if (item.HEADER === undefined) { item.HEADER = 'indéfini'; } // or if (typeof item.HEADER === 'undefined') { item.HEADER = 'indéfini'; }
Originally posted 2013-11-10 00:10:33.