'未定义'当试图访问json响应时

时间:2016-08-01 15:26:13

标签: javascript jquery json ajax

我的烧瓶应用程序包含返回以下内容的代码:

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条目时,我得到了“未定义”#39;作为输出。我做错了什么?

2 个答案:

答案 0 :(得分:7)

您尚未解析JSON:

success: function(data) {
    var response = JSON.parse(data);
    console.log(response);
    console.log(response.url);
}

答案 1 :(得分:3)

你也可以使用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);
            }
        });
    });
});
相关问题