1

$.ajaxRails プロジェクトで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)

(Firebug コンソールによると) 正しい json 文字列が返されたようです。これは次のようになります。

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

ただし、「TypeError: 結果が null です」というエラーが表示されます。

私が使用する場合

alert(data_response.responseText)

関数ではcomplete、json 文字列を取得します。したがって、問題は解析にあるようです。(???)

4

2 に答える 2

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 に変換してください。

于 2012-11-13T16:02:02.273 に答える
1

ドゥー!ありがとう@KevinB、あなたのコメントはsuccessそれcompleteを解決しました。とても簡単です。後者の代わりに前者を使用してください。

jQuery ->
  testAjax()
  #initialize()


testAjax = ->
  $.ajax
    url: "/gmap/test"
    data: "id=2"
    type: "GET"
    contentType: "application/json"
    dataType: "json"
    success: (data) ->
      alert(data.name)
于 2012-11-13T16:24:59.333 に答える