TheAce
TheAce

Reputation: 122

Parsing AJAX Response

I would like to just say thank you for anyone that helps. But I am not able to parse my AJAX response properly:

My AJAX Request:

$('#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>"""

Results:

id

logger1 undefined

points

[object Object] undefined

reports

[object Object] undefined

capacity

16070400000 undefined

True Results:

{
"id": "logger1",
"points": [
    {
        "id": "00000000/pulse_1",
        "interval": 300000,
        "enabled": true
    }
],
"reports": [
    {
        "collector": "[email protected]",
        "interval": 300000,
        "enabled": true
    }
],
"capacity": 16070400000
}

Upvotes: 0

Views: 111

Answers (3)

000
000

Reputation: 27247

EDITED answer based on comments

JSON.stringify is what you are looking for. stringify takes a parameter for pretty-printing: 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)

Upvotes: 1

Greg Burghardt
Greg Burghardt

Reputation: 18783

The append method in jQuery does not do template tag replacement in the current context. It just takes a string of HTML, another jQuery collection or a DOM node.

You'll want to do something like:

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

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

Upvotes: -1

SteamDev
SteamDev

Reputation: 4404

It is working correctly. Your undefineds are accurate, since none of your values are objects with an id property. All of your values are either arrays or strings.

Upvotes: 1

Related Questions