无法在Rails中获得JSON

时间:2014-07-01 22:45:10

标签: jquery ruby-on-rails ajax json

我正在尝试使用jQuery的ajax方法向rails发布帖子请求。如果我发送form.elements(),请求的内容类型是urlencoded并且rails能够使用正确的值填充params,但浏览器期望响应为html,因此respond_to format.json会抛出异常(ActionController :: UnknownFormat)。

coffeescript:
$(document).on(
    click: ->
      $.ajax
        url: "/projects.json"
        type: "POST"
        contentType: 'json'
        dataType: 'json'
        data: JSON.stringify($('form#new_project').elements())
        success: activateProgressBar
      return false
    , '#submit-button'
  )

Log:    
Processing by ProjectsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Eonu3puxtkBUTtyDQNbE059Racfrwu06q/FzwKm1hWE=", "BusinessUnit"=>{"sbu"=>"2"}, "project"=>{"parent_id"=>"1", "project_num"=>"04479", "client_id"=>"101", "project_type_id"=>"1", "name"=>"ascac", "summary"=>"acacac"}, "User"=>{"approver_id"=>"115"}}

如果我使用serializeArray设置数据,请求将作为JSON进行,但params没有表单数据。

Coffeescript:
  $(document).on(
    click: ->
      $.ajax
        url: "/projects.json"
        type: "POST"
        contentType: 'json'
        dataType: 'json'
        data: JSON.stringify($('form#new_project').serializeArray())
        success: activateProgressBar
      return false
    , '#submit-button'
  )

Log:
Processing by ProjectsController#create as JSON
Parameters: {"action"=>"create", "controller"=>"projects", "format"=>"json"}

知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

我最终根据@ Iceman的暗示和大量谷歌搜索改变了视图中的form_for:

form_for @proj, remote: true, html: {:'data-type' => 'application/json'} do |f|

数据来自参数,但不是以参数格式:

Parameters: {"_json"=>[{"name"=>"utf8", "value"=>"✓"}, {"name"=>"BusinessUnit[sbu]", "value"=>"2"}, {"name"=>"project[parent_id]", "value"=>"1"}, {"name"=>"project[project_num]", "value"=>"04512"}, {"name"=>"project[client_id]", "value"=>"101"}, {"name"=>"User[approver_id]", "value"=>"115"}, {"name"=>"project[project_type_id]", "value"=>"1"}, {"name"=>"project[name]", "value"=>"sxasx"}, {"name"=>"project[summary]", "value"=>"sxasx"}], "project"=>{}}

我用这段代码把它变成一个可用的哈希:

@form_data = Hash[ params[:_json].map(&:values) ]

我不知道这是否是正确的方法,但它确实有效,我需要继续其他事情。

顺便说一下,ajax电话最终看起来像这样:

  form_data = JSON.stringify($('#new_project').serializeArray())
  $.ajax
    url: "/projects.json"
    type: "POST"
    contentType: 'application/json'
    dataType: 'json'
    data: form_data
    success: activateProgressBar