我试图在xmlHttp.responseText的数组nr#1为空时执行某个条件。 但我无法让它发挥作用。别知道错了..
来自php 我使用json_encode发送数组。 在javascipt中,我使用JSON.parse()方法来解析数组。
此数组中只有2个字符串[“”,“”]
我正在尝试检测第一个数组是否为空,因此提醒一些事情。
让我们看看我的代码:
var str=xmlHttp.responseText;
var res=JSON.parse(str);
我尝试了以下几行,但没有一个在工作!
if (res[0]=null) {
alert('hey, it´s null');
}
AND
if (res[0]==null) {
alert('hey, it´s null');
}
AND
if (res[0]=="null") {
alert('hey, it´s null');
}
AND
if (res[0]=="") {
alert('hey, it´s null');
}
I have used PHP to echo the code json and i get:
["null",""]
实际上错了吗?
答案 0 :(得分:1)
如果你得到了json数据:
["null",""]
暗示
$data = array(
0 => "null",
1 => ""
);
$json = json_encode($data);
echo $json; ---> this result like yours....["null",""]
echo "<br />";
$res = json_decode($json); ----> you must decode your Json first...
echo $res[0]; -----> this code result is "null" like you wanted...
以下语句会告诉您对象是否为空。
if (res[0]==null) { -----> it always result "[" not the data "null"....
alert('hey, it´s null');
}
因此,首先必须解码json数据,然后检查对象。