我可能误解了JSON,但为什么这段代码不起作用?
HTML
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div class="response">
Name: <span class="name"></span><br>
Password: <span class="password"></span><br>
</body>
</html>
MAIN.JS
$(document).ready(function(){
$.ajax({
type: "POST",
url: 'action.php',
dataType: 'json',
success: function(msg){
$.each(msg, function(index, value){
if (index == 'name') { $('.name').html(value.name); }
if (index == 'password') { $('.password').html(value.password); }
});
},
error: function(){
$('.response').html("An error occurred");
}
});
});
action.php的
<?php
$array = array(
0 => array(
'name' => "Charlie",
'password' => "none"
),
1 => array(
'name' => "Tree",
'password' => "tree"
)
);
echo json_encode($array);
?>
答案 0 :(得分:3)
在您的javascript中,index
将为'0'和'1',永远不会'name'和'value':
success: function(msg){
$.each(msg, function(index, value){
$('.name').html(value.name);
$('.password').html(value.password);
});
},
当然,正如现在这样,你将两次设置你的领域,只有最后一个将“坚持”
如果您只想使用'Charlie'结果,那么
success: function(msg){
$('.name').html(msg[0].name);
$('.password').html(msg[0].password);
},
和'Tree',只需将数组下标更改为1
答案 1 :(得分:0)
应该是
if (index == 'name') { $('.name').html(value); }
if (index == 'password') { $('.password').html(value); }