php - 如何检查一个对象是否为空?

标签 php javascript json

我正在尝试执行一个条件,如果 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/

相关文章:

php - 在 MySQL 的 BLOB 列中搜索值

php - Zend Framework 1.12 Db Select - 嵌套 WHEREs 在条件中使用问号的多个值

php - 无法从命令行访问 phpmyadmin

javascript - 在数组中加载大量条目会导致网页卡住

javascript - 奇怪的 Angular-ChartJS 问题,无法在 Ionic App 中正确显示

javascript - 如何比较两个对象并获得它们差异的键值对?

json - 如何在 Firebase 中存储时间值,特别是仅小时和分钟?

php - php脚本中最佳的MYSQL查询数是多少?

javascript - 我无法进入嵌套 JSON 对象,但只是有时

json - 将多个值反序列化为单个属性