使用$ .parseJSON解析JSON对象将返回null

时间:2012-11-13 15:26:42

标签: jquery ajax ruby-on-rails-3 json coffeescript

我在rails项目中通过$.ajax请求JSON响应。

jQuery ->
  testAjax()


testAjax = ->
  $.ajax
    url: "/gmap/test"
    data: "id=2"
    type: "GET"
    dataType: "json"
    complete: (data_response) ->
      result = $.parseJSON(data_response)
      alert(result.name)

我似乎得到了一个正确的json字符串(根据Firebug控制台),看起来像这样:

{"name":"Space Needle","latitude":47.620471,"longitude":-122.349341}

但是,我收到错误抱怨“TypeError:result is null”

如果我使用

alert(data_response.responseText)

complete函数中,我得到了json字符串。所以问题似乎是解析。 (???)

2 个答案:

答案 0 :(得分:1)

完整回调的第一个参数是jqXHR对象。试试这个:

#Scope the result outside of the testAjax function
result = null

testAjax = ->
  $.ajax
    url: "/gmap/test"
    data: "id=2"
    type: "GET"
    dataType: "json"
    success: (data) ->
      #set the data to your result
      result = data
    complete: ->
      alert result.name

随意编辑我的回复,将我的更改转换为有效的coffeescript。

答案 1 :(得分:1)

DOOH!感谢@KevinB,您对successcomplete的评论已经解决了。这很简单,使用前者而不是后者:

jQuery ->
  testAjax()
  #initialize()


testAjax = ->
  $.ajax
    url: "/gmap/test"
    data: "id=2"
    type: "GET"
    contentType: "application/json"
    dataType: "json"
    success: (data) ->
      alert(data.name)