[英]array.length returns number of strings instead of number of array elements
[英]JSON length in javascript returns number of character instead of number of array elements
嗨,我有问题,我尝试了类似的事情并回答,但Object.keys(data).length都没有帮助我。 这是我的JSON
{
"POSTS": [
[
{
"term_id": 1,
"name": "Uncategorized",
"slug": "uncategorized",
"term_group": 0,
"term_taxonomy_id": 1,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 1,
"filter": "raw",
"cat_ID": 1,
"category_count": 1,
"category_description": "",
"cat_name": "Uncategorized",
"category_nicename": "uncategorized",
"category_parent": 0
},
{
"term_id": 2,
"name": "Nova",
"slug": "nova",
"term_group": 0,
"term_taxonomy_id": 2,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 1,
"filter": "raw",
"cat_ID": 2,
"category_count": 1,
"category_description": "",
"cat_name": "Nova",
"category_nicename": "nova",
"category_parent": 0
},
{
"term_id": 3,
"name": "nova1",
"slug": "nova1",
"term_group": 0,
"term_taxonomy_id": 3,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 1,
"filter": "raw",
"cat_ID": 3,
"category_count": 1,
"category_description": "",
"cat_name": "nova1",
"category_nicename": "nova1",
"category_parent": 0
},
{
"term_id": 4,
"name": "nova2",
"slug": "nova2",
"term_group": 0,
"term_taxonomy_id": 4,
"taxonomy": "category",
"description": "",
"parent": 3,
"count": 1,
"filter": "raw",
"cat_ID": 4,
"category_count": 1,
"category_description": "",
"cat_name": "nova2",
"category_nicename": "nova2",
"category_parent": 3
},
{
"term_id": 5,
"name": "nova3",
"slug": "nova3",
"term_group": 0,
"term_taxonomy_id": 5,
"taxonomy": "category",
"description": "",
"parent": 3,
"count": 1,
"filter": "raw",
"cat_ID": 5,
"category_count": 1,
"category_description": "",
"cat_name": "nova3",
"category_nicename": "nova3",
"category_parent": 3
}
]
],
"success": 1
}
这是我的JavaScript代码:
<select id ="new" name="new"></select>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
var select = document.getElementById("new");
$.ajax({
type: "POST",
url: "wp-content/themes/twentyfourteen/ajax.php", // this script returns my JSON
data: ({canum: 0}),
success: function(data){
console.log(Object.keys(data).length);
}
});
});
</script>
这返回我1445作为长度而不是我需要的5,如何在JSON
中获取段数如何获取5而不是字符数?
你能帮我吗 ? 谢谢。
您需要JSON.parse
数据。 就您而言,它不是作为application/json
发送的,而是作为text/html
发送的。
您的成功功能应执行以下操作:
success: function(data){
data = JSON.parse(data);
console.log(Object.keys(data).length);
}
或者,如果您不想使用JSON.parse
数据,而让jQuery管理它,则可以尝试此操作。 您可以在服务器中的config对象中传递期望的dataType
:
$.ajax({
type: "POST",
url: "wp-content/themes/twentyfourteen/ajax.php", // this script returns my JSON
data: ({canum: 0}),
success: function (data) {
console.log(Object.keys(data).length);
},
dataType: 'json' // <- Add this
});
最后一个选择是,您可以使用$ .getJson()代替,它是上述方法的简写版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.