4

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+"<td title='"+item.DESCRIPTION+"'>"+item.ID+"</td>" +
            "<td>"+
                "Header : "+item.HEADER + '<br/>' +
                "Méthode : "+item.METHODE +  '<br/>' +
                "PostBody : "+item.POSTBODY +  '<br/>' +
                "URL : "+item.URL +  '<br/>' +
                "ParseReponse : "+item.PARSEREPONSE +  '<br/>' +
            "</td>" +

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?

4

4 に答える 4

9

concat内で条件付き/論理ORチェックをすばやく実行できます。

"Header : " + (item.HEADER || '') + '<br/>' +

そのため、代わりに空の文字列が発生しますitem.HEADERundefinedもちろん、などのより表現力豊かな文字列を使用することもできます"empty"

于 2012-08-06T13:59:53.470 に答える
4
if (typeof variable == "undefined")
{
    // variable is undefined
}
于 2012-08-06T14:00:29.830 に答える
1

三項演算子を使用します... ( test ? do if true : do if false )

...+( item.HEADER ? item.HEADER : "something french" )+...
于 2012-08-06T14:00:47.570 に答える
0

次のように簡単に実行できます。

if (item.HEADER === undefined) {
    item.HEADER = 'indéfini';
}

// or 

if (typeof item.HEADER === 'undefined') {
    item.HEADER = 'indéfini';
}
于 2012-08-06T14:00:18.773 に答える