Javascript 尝试解析JSON时未定义
我正在尝试用JQuery解析JSON响应:Javascript 尝试解析JSON时未定义,javascript,jquery,json,ajax,Javascript,Jquery,Json,Ajax,我正在尝试用JQuery解析JSON响应: <script> $(document).ready(function() { $("button").click(function() { $.ajax({ url : 'test.php', type : 'GET', data : { name : "P
<script>
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url : 'test.php',
type : 'GET',
data : {
name : "Peter",
},
dataType : 'json',
success : function(response) {
console.log(response);
alert(response.name)
},
error : function() {
console.log("error")
}
});
});
});
</script>
当我发出
alert(JSON.stringify(response))代码>我得到{“results”:[{“id”:“4”,“name”:“Peter”}]}
,因此肯定存在有效的JSON。在响应中
没有属性名称
name
在results
数组的第一个元素中有,所以要获得name,需要执行以下操作
console.log(response.results[0].name)
response是一个在results中包含数组的对象,您需要迭代response.results,或者如果您确定它只有一个元素,请使用response.results[0]。nameJSON数据包含数组,因此您需要使用索引:
var data={“results”:[{“id”:“4”,“name”:“Peter”}]}
document.write(data.results[0].name)
response.results[0].name
这样一个问题怎么能得到投票?
console.log(response.results[0].name)