“未定义”试图访问JSON响应时
问题描述:
我的瓶的应用程序有一个返回下面的代码:“未定义”试图访问JSON响应时
return json.dumps({'status': 'OK','url': 'www.blahg.com'})
我的JavaScript代码如下所示:
$(function() {
$('#mainbutton').click(function() {
$.ajax({
url: '/buttonclick',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
console.log(response.url);
},
error: function(error) {
console.log(error);
}
});
});
});
第一个控制台日志看起来是正确的: {"status": "OK", "url": "www.blahrg.com"}
,但是当我尝试访问url
条目时,我得到'undefined'作为输出。我究竟做错了什么?
答
您还可以使用dataType
拥有jQuery的解析它为您提供:
$(function() {
$('#mainbutton').click(function() {
$.ajax({
url: '/buttonclick',
data: $('form').serialize(),
type: 'POST',
dataType: 'json', // this bit here
success: function(response) {
console.log(response);
console.log(response.url);
},
error: function(error) {
console.log(error);
}
});
});
});
答
您还没有解析的JSON:
success: function(data) {
var response = JSON.parse(data);
console.log(response);
console.log(response.url);
}
你确定这是不是一个字符串''{”状态“:”确定“,”网址“:”www.blahrg.com“}''?尝试'var response = JSON.parse(response);' –
有可能'response'是一个JSON字符串?首先尝试使用'JSON.parse' – stackoverfloweth
[如何访问JSON对象名称/值?]的副本(http://stackoverflow.com/questions/10895306/how-to-access-json-object-name- value) – davidism