0

我有一条如下所示的 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。很困惑。

4

1 回答 1

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);
      }
    })
  })
于 2013-07-29T21:54:35.573 回答