Jquery 使用$.parseJSON解析JSON对象返回空值
我在rails项目中通过Jquery 使用$.parseJSON解析JSON对象返回空值,jquery,ajax,ruby-on-rails-3,json,coffeescript,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(res
$.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为null”
如果我使用
alert(data_response.responseText)
在
complete
函数中,我得到了json字符串。所以问题似乎在于解析。(???)完整回调的第一个参数是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
请随意编辑我的回复,将我的更改转换为有效的咖啡脚本。Dooh!谢谢@KevinB,你关于
成功
和完成
的评论已经解决了这个问题。很简单,用前者代替后者:
jQuery ->
testAjax()
#initialize()
testAjax = ->
$.ajax
url: "/gmap/test"
data: "id=2"
type: "GET"
contentType: "application/json"
dataType: "json"
success: (data) ->
alert(data.name)
返回肯定是一个字符串。如果使用parseJSON解析已经是JSON(设置了正确的头)的内容,则会引发该错误。您不需要解析JSON,设置
dataType:“JSON”
会自动执行该操作,这意味着您正在尝试解析JavaScript对象。放入真实代码,不是psuedo代码它是coffeescript不是伪代码。@Korikulum完整回调不包含解析的json响应,它的第一个参数是jqXHR对象:@donsteffenski回复你的建议编辑(被其他评论员拒绝了),是的,这正是我想要的。如果你要回答这个主题中的问题,也许现在是学习咖啡脚本的好时机,@Kevin?:)@马修布兰卡特老实说,我不认为咖啡脚本存在的理由,但感谢你修复它!在我开始使用它之前,我也有同样的想法。您可能会惊讶地发现,需要编写的代码要少得多,而添加的一些语言特性(默认参数、splats、列表理解等)又有多好。也就是说,使用vanilla js甚至TypeScript可能会更好