解析AJAX响应

时间:2014-05-19 20:44:17

标签: javascript jquery ajax coffeescript lint

我想对任何有帮助的人说声谢谢。但我无法正确解析我的AJAX响应:

我的AJAX请求:

$('#sumbit_LoggingGet').on 'click', ->
username = $('#login_username').val()
password = $('#login_password').val()
mac_id = $('#login_LoggingGetmac').val()
id = $('#login_LoggingGetid').val()

$.ajax
  type: "GET"
  url: start_url + mac_id + "/log-config/" + id
  dataType: "json"
  crossDomain: true
  cache: false
  beforeSend: beforeSend(username, password)

  success: (data) ->
    console.dir data
    successMessage("""<h1>Logging Get Results</h1>""")
    clearColor(areaText = '#header_username')
    clearColor(areaText = '#header_password')
    clearColor(areaText = '#header_LoggingGetmac')
    clearColor(areaText = '#header_LoggingGetid')

    for key,value of data
      $('#data-results').append """<br>
      <h3><span style="color: #0000CD;"> #{key}</span></h3>
      <br><h4> #{value} #{value.id}</h4><br>"""

结果:

ID

logger1 undefined

[object Object] undefined

报告

[object Object] undefined

容量

16070400000 undefined

真实结果:

{
"id": "logger1",
"points": [
    {
        "id": "00000000/pulse_1",
        "interval": 300000,
        "enabled": true
    }
],
"reports": [
    {
        "collector": "collector1@talkrnd.enernoc.net",
        "interval": 300000,
        "enabled": true
    }
],
"capacity": 16070400000
}

3 个答案:

答案 0 :(得分:1)

工作正常。您的undefineds是准确的,因为您的所有值都不是objects,且id属性。您的所有值均为arraysstrings

答案 1 :(得分:1)

基于评论的编辑回答

JSON.stringify正是您要找的。 stringify采用漂亮打印的参数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_native_JSON

$.ajax
  type: "GET"
  url: start_url + mac_id + "/log-config/" + id
  dataType: "json"
  crossDomain: true
  cache: false
  beforeSend: beforeSend(username, password)

  success: (data) ->
    console.dir data
    successMessage("""<h1>Logging Get Results</h1>""")
    clearColor(areaText = '#header_username')
    clearColor(areaText = '#header_password')
    clearColor(areaText = '#header_LoggingGetmac')
    clearColor(areaText = '#header_LoggingGetid')
    $('#data-results').html JSON.stringify(data,undefined,2)

答案 2 :(得分:-1)

jQuery中的append方法不会在当前上下文中替换模板标记。它只需要一串HTML,另一个jQuery集合或DOM节点。

你想要做的事情如下:

var html = "...".replace(/#\{(\w+)\}/g, function(match, tag) {
    return data[tag] || "";
});

$(...).append(html);