Ajax 向Sinatra路由发送的jQuery JSON无法正常工作

Ajax 向Sinatra路由发送的jQuery JSON无法正常工作,ajax,json,sinatra,Ajax,Json,Sinatra,我有一条Sinatra路线,看起来像这样: post '/participants/create' do puts request.body.read end 我使用jQuery帖子来实现它: javascript: $('#contact').on('submit',function () { $.ajax({ url: 'participants/create', dataType: 'json', contentType: 'appli

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

post '/participants/create' do
  puts request.body.read
end
我使用jQuery帖子来实现它:

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
。非常困惑。

我有点忘了,因为我试图把所有的东西都塞进评论中,所以我只回答

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);
      }
    })
  })

你阻止表单提交了吗?嗯。。。好问题。我需要使用prevent默认值,不是吗?请在处理程序的主体中尝试
p params
。Sinatra有时会做一些奇怪的参数处理。Dominic,试试
function(event){
event.preventDefault()
。另外,Sinatra很好,可以为您将POST数据放入
参数
对象/帮助程序,无需阅读请求正文。请看一看,我也听到了一些好消息。最后,尝试使用
停止200,参数进行响应。检查
而不是
放置
…谢谢。解决了问题,但关于JSON到HTTP服务器。@DominicBou Samra很高兴听到你把它整理好了。嗯,第二个答案让我有点困惑。你说的是将HTTP发送到Sinatra,然后将JSON发送到浏览器?为什么不将JSON发送到两者?还有..在这两个例子中,参数都是空的,但request.body.read有数据。@DominicBou Samra问题应该是,为什么要添加在服务器上解析JSON数据的额外转换步骤?Sinatra(和其他HTTP应用服务器/框架)在不使用JSON的情况下可以很好地处理HTTP POST。但是,Javascript可以很好地处理JSON,而且在库中有很多对它的支持。我让它工作了,这里有一个repo在这个例子中,参与者/create方法需要能够接受来自多个来源的输入(不仅仅是web表单).也许我应该让它同时响应HTTP和JSON。