我忘记了一点,因为我试图将所有内容都塞进评论中,所以我会回答。
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);
}
})
})