我正在尝试执行一个条件,如果 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",""]
那么到底出了什么问题?
最佳答案
如果你得到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 数据,然后检查对象。
关于php - 如何检查一个对象是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18620526/