2016-08-01 121 views
1

我的瓶的應用程序有一個返回下面的代碼:「未定義」試圖訪問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'作爲輸出。我究竟做錯了什麼?

+0

你確定這是不是一個字符串''{」狀態「:」確定「,」網址「:」www.blahrg.com「}''?嘗試'var response = JSON.parse(response);' –

+0

有可能'response'是一個JSON字符串?首先嚐試使用'JSON.parse' – stackoverfloweth

+1

[如何訪問JSON對象名稱/值?]的副本(http://stackoverflow.com/questions/10895306/how-to-access-json-object-name- value) – davidism

回答

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); 
      } 
     }); 
    }); 
}); 
6

您還沒有解析的JSON:

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