Javascript 从JSON数组读取
这是我的JSON数组:Javascript 从JSON数组读取,javascript,jquery,json,Javascript,Jquery,Json,这是我的JSON数组: msg={"userid":"82","0":"82","first":"A","1":"A","last":"B","2":"B","email":"w@w.com","3":"w@w.com","username":"n","4":"n","password":"o","5":"o","hash":"3242","6":"3242","active":"0","7":"0","date":"0","8":"0","holding":"","9":"","ip":"0"
msg={"userid":"82","0":"82","first":"A","1":"A","last":"B","2":"B","email":"w@w.com","3":"w@w.com","username":"n","4":"n","password":"o","5":"o","hash":"3242","6":"3242","active":"0","7":"0","date":"0","8":"0","holding":"","9":"","ip":"0","10":"0","attempts":"0","11":"0"}
现在,我试图得到不同的部分,但我尝试没有工作。我试过了
msg.first //returns undefined
msg['first'] // returns undefined
msg[0] // returns that first bracket {
我相信这很容易解决,我只是不知道问题是什么。这个数组由一些php使用json_encode输出。如果该代码是相关的,请让我知道,我会把它。谢谢 如果msg[0]返回第一个括号,则JSON会被解释为字符串。这可以通过jQuery的parseJSON轻松解决:
我试过了
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function display(data) {
$.each(data, function(key,value) {
$('#userDetails').append('<li>' + key + " : " +'<span class="ui-li-aside">'+ value +'</span></li>');
});
}
$(document).ready(function() {
msg= {"userid":"82",
"0":"82",
"first":"A",
"1":"A",
"last":"B",
"2":"B",
"email":"w@w.com",
"3":"w@w.com",
"username":"n",
"4":"n",
"password":"o",
"5":"o",
"hash":"3242",
"6":"3242",
"active":"0",
"7":"0",
"date":"0",
"8":"0",
"holding":"",
"9":"",
"ip":"0",
"10":"0",
"attempts":"0",
"11":"0"}
display(msg);
});
</script>
</head>
<body>
<div id="userDetails"></div>
</body>
</html>
在使用jQueryAjax函数时,我经常遇到这个问题。您需要指定您期望的是json响应 如果进行此调用,则返回的数据变量将是字符串
$.ajax({
type: "POST",
url: '/controller/function',
data: {
'parameter_name' : value,
},
success: function(data){
console.log(data.blah); // Undefined
},
});
但是如果将数据类型指定为json,那么数据变量将是json对象
$.ajax({
dataType: "json", // Have to include this
type: "POST",
url: '/controller/function',
data: {
'parameter_name' : value,
},
success: function(data){
console.log(data.blah); // Defined!!!
},
});
如果您的数据实际上在javascript变量中(如您所示),那么在这里似乎可以正常工作:仅供参考,答案中显示的代码不是数组或JSON,而是javascript文本对象声明。JSON是一种文本格式,用于以文本形式交换结构化数据。+1。请注意,尽管all JSON是一个字符串,但问题中显示的代码是一个对象文本,而不是JSON,也不是数组,b如果通过Ajax请求检索JSON,那么jQuery的Ajax方法将自动解析返回的JSON,并将结果对象提供给成功回调。如果/controller/function页面返回内容类型为application/JSON的响应,那么$.Ajax将自动解析它。
$.ajax({
dataType: "json", // Have to include this
type: "POST",
url: '/controller/function',
data: {
'parameter_name' : value,
},
success: function(data){
console.log(data.blah); // Defined!!!
},
});