我尝试向控制器中的create
操作提交ajax post请求,但我在ajax undefined
函数中获得了success
而不是json响应。我需要一个json响应,因为我正在构建一个单页应用程序。
我正在使用render :json => {name: "jim"}.to_json
。这是正确的解决方法吗?还是我缺少一些关于ajax请求的基本信息?
非常感谢任何帮助。
客户端ajax发布请求:
submit_click: ->
$.post "/responses",
type: "POST"
dataType: "json"
contentType: "application/json"
charset="utf-8"
response:
image_id: @image_name
data: @data_pool
success: (json) ->
console.log json
响应控制器中的操作:
def create
@response = Response.new(response_params)
if @response.save
count = count_completed_responses
if count < 20
render :json => {name: "jim"}.to_json
end
end
end
编辑:我可以在Chrome开发者控制台的网络标签中看到响应 - {name:&#34; jim&#34;}。为什么我不能在ajax成功回调中访问它?
第二次编辑:我实际上是在$post
函数之后使用以下内容来实现此目的:
.done (data)
console.log data
任何人都知道为什么这样有效,而另一种方式不是?
答案 0 :(得分:0)
应该如下所示
submit_click: ->
$.post "/responses",
contentType: 'application/json; charset=utf-8'
dataType: 'json'
response:
image_id: @image_name
data: @data_pool
success: (json) ->
console.log json
希望它对您有用