2013-07-25 2 views
0

나는이처럼 보이는시나 경로를 가지고 :jQuery를 JSON 포스트가 제대로 작동하지

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

양식 제출을 막았습니까? – Musa

+0

Hmmmmm ... 좋은 질문입니다. preventDefaults를 사용해야합니까? –

+2

당신의 핸들러 몸체에'p params'를 시도하십시오. Sinatra는 가끔 이상한 param 처리를합니다. – AlexQueue

답변

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을 자바 스크립트로 보내는 것이 가장 효과적이라는 것을 발견했다. 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); 
     } 
    }) 
    }) 
+0

감사합니다. 문제를 정렬했지만 JSON 대 HTTP 서버에 대한 좋은 점. –

+0

@ DominicBou-Samra 기쁜 소식을 들려주기를 기원합니다. – iain

+1

흠 나는 두 번째 대답으로 약간 혼란 스럽다. Sinatra에 HTTP를 보내고 브라우저에 JSON을 보냅니다. 두 가지 모두에 JSON을 사용하지 않는 이유는 무엇입니까? 또한 .. 두 예제 모두에서 params는 비어 있지만 request.body.read에는 데이터가 있습니다. –

관련 문제