javascript Jquery Ajax 和 Json:如何检查是否未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11829773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Ajax and Json : How to check if undefined
提问by timmalos
I got this Jquery code :
我得到了这个 Jquery 代码:
$.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'.
所以我从我的服务器收到了 JSON 响应,但并非所有字段都已满。有时 item.HEADER 或 item.METHODE 无法定义,所以我的表中出现“未定义”文本。问题是,我是法国人,我想要不同的文本,而不是这个“未定义”。
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?
那么如何测试变量是否已定义?或者更好的是,如果变量未定义,是否可以将此“未定义”文本更改为不同的文本?
回答by jAndy
You can do a quick conditional / logical-OR check within your concat:
您可以在 concat 中进行快速条件/逻辑或检查:
"Header : " + (item.HEADER || '') + '<br/>' +
so now, if item.HEADER
is undefined
we will encounter the empty string instead. Of course you could also use a more expressive string like "empty"
or whatnot.
所以现在,如果item.HEADER
是,undefined
我们将遇到空字符串。当然,您也可以使用更具表现力的字符串,例如"empty"
或诸如此类。
回答by DavidS
if (typeof variable == "undefined")
{
// variable is undefined
}
回答by Billy Moon
Use a ternary operator... ( test ? do if true : do if false )
使用三元运算符...(测试?如果为真则执行:如果为假则执行)
...+( item.HEADER ? item.HEADER : "something french" )+...
回答by Stephen
easily done like so:
像这样轻松完成:
if (item.HEADER === undefined) {
item.HEADER = 'indéfini';
}
// or
if (typeof item.HEADER === 'undefined') {
item.HEADER = 'indéfini';
}