jQuery JSON发布到Sinatra路由无法正常工作

时间:2013-07-25 23:52:22

标签: ajax json sinatra

我有一条看起来像这样的Sinatra路线:

post '/participants/create' do
  puts request.body.read
end

我正在使用jQuery POST:

javascript:
  $('#contact').on('submit',function () {
    $.ajax({
      url: 'participants/create',
      dataType: 'json',
      contentType: 'application/json',
      type: 'POST',
      data : JSON.stringify({ name: "Dom"}),
      success: function(json) {
        alert('all done');
      }
    })
  })

无论出于何种原因,正文总是空的,而request.content-type始终是application/x-www-form-urlencoded。很困惑。

1 个答案:

答案 0 :(得分:1)

我忘记了一点因为我试图将所有内容都塞进评论中,所以我只是回答。

post '/participants/create', :provides => :json do
  # I'd use a 201 as the status if actually creating something,
  # 200 while testing.
  # I'd send the JSON back as a confirmation too, hence the
  # :provides => :json
  data = JSON.parse params
  # do something with the data, then…
  halt 200, data.to_json
  # halt because there's no need to render anything
  # and it's convenient for setting the status too
end


javascript:
  $('#contact').on('submit',function (event) {
    event.preventDefault();
    $.ajax({
      url: 'participants/create',
      dataType: 'json',
      contentType: 'application/json',
      type: 'POST',
      data : JSON.stringify({ name: "Dom"}),
      accepts: "application/json",
      success: function(json) {
        alert(json);
      }
    })
  })

总的来说,为什么要将JSON发送到HTTP服务器?我发现最好将HTTP发送到服务器,JSON发送到javascript,因为这是他们更喜欢的。 YMMV。

post '/participants/create', :provides => :json do
  # Do something with the params, then…
  halt 200, params.to_json 
end

javascript:
  $('#contact').on('submit',function (event) {
    event.preventDefault();
    $.ajax({
      url: 'participants/create',
      dataType: 'json',
      type: 'POST',
      data : { name: "Dom"}, // or $(event.target).serialize()
      accepts: "application/json",
      success: function(json) {
        alert(json);
      }
    })
  })