jQuery和JSON阵列 - 如何检查,如果数组为空或未定义? [英] JQuery and JSON array - How to check if array is empty or undefined?
问题描述
我需要的PHP数组传递给jQuery的一些任务。 PHP的数组会话创建,然后jQuery的json_en codeD。从那以后,我就这个变量存储窗口的js命名空间,以便使用数组在我的jQuery脚本。
如果(使用isset($ _ SESSION ['MySession的'])){
$ json_array = json_en code($ php_array);
}<脚本>
<?PHP的回声window.json_from_php =$ json_array。 ?>
< / SCRIPT>
我需要做的事情就是检查这个数组是否在所有存在/空/做任何事情之前不确定的。检查子句成功为'不确定'操作数而不是休息。如何检查jQuery的数组是否为空或不?
这是初始化后json_en $ C $光盘阵列的输出,当有在$ php_array没有任何元素:
字符串[](长度= 4)
这里是jQuery的:
$(函数(){
VAR的结果= $('#结果');
VAR js_array = window.json_from_php;
变种数= js_array.length; 如果((typeof运算window.json_from_php ===未定义)||(js_array === NULL)||(jQuery.isEmptyObject(js_array))||(计数=== 0)){
$('< P> Array为空< / P>')appendTo(结果)。
}
其他{
jQuery.each(js_array,功能(键,VAL){
$('< UL><李ID =+按键+'>'+ VAL +'< /李>< / UL>')。appendTo(结果);
});
}
});
这是我如何检查空/空JSON数组
如果(js_array == ||未定义== js_array空|| js_array.length == 0){
$('< P> Array为空< / P>')appendTo(结果)。
}
如果您的JSON数组是 []
,那么你可能需要添加像
如果(js_array == ||未定义== js_array空|| js_array.length == 0 ||(js_array.length == 1安培;&安培; js_array [0] = =))
I need to pass php array to jquery for some tasks. The php array is created for SESSION and then json_encoded for jquery. After that I'll store that variable to window js namespace in order to use the array in my jquery script.
if(isset($_SESSION['mySession'])){
$json_array = json_encode($php_array);
}
<script>
<?php echo "window.json_from_php = ".$json_array; ?>
</script>
The thing i need to do is to check whether this array exist at all/is empty/undefined before doing anything. The check clause succeeds for 'undefined' operand but not for the rest. How can I check in jquery whether array is empty or not?
This is the output of the json_encoded array after initialization, when there isn't any elements in the $php_array:
string '[""]' (length=4)
And here is the jquery:
$(function() {
var results = $('#results');
var js_array = window.json_from_php;
var count = js_array.length;
if ((typeof window.json_from_php === 'undefined') || (js_array === null) || (jQuery.isEmptyObject(js_array)) || (count === 0)) {
$('<p>Array is empty.</p>').appendTo(results);
}
else {
jQuery.each(js_array,function(key,val){
$('<ul><li id="'+key+'">'+val+'</li></ul>').appendTo(results);
});
}
});
This is how I check for an empty/null json array.
if (js_array == undefined || js_array == null || js_array.length == 0){
$('<p>Array is empty.</p>').appendTo(results);
}
If your json array is [""]
then you may need to add something like
if (js_array == undefined || js_array == null || js_array.length == 0 || (js_array.length == 1 && js_array[0] == ""))
这篇关于jQuery和JSON阵列 - 如何检查,如果数组为空或未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!