레일즈 루비 코드에서 클라이언트에게 json 응답을 보내려고합니다. 레일에서 루비를 처음 접했을 때 나는 이것을 어떻게 할 수 있을지 모른다. 성공적으로 여기 내 자바 스크립트 코드가 success = 1 and error = 0
이json 응답을 클라이언트에 다시 전달하는 방법
내 컨트롤러
class ContactsController < ApplicationController
respond_to :json, :html
def contacts
error = 0
success = 1
@contacts = Contact.new(params[:contact])
if @contacts.save
respond_to do |format|
format.json { render :json => @result.to_json }
end
else
render "new"
end
end
end
입니다 아래에 내 코드를 참조하십시오 보낼 것을 절약 할 수 있다면 데이터가 데이터베이스에 저장하지 않을 경우 JSON 데이터로 error = 1 and success = 0
를 보낼과
$('.signupbutton').click(function(e) {
e.preventDefault();
var data = $('#updatesBig').serialize();
var url = 'contacts';
console.log(data);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
봐 작동합니다 JSON 데이터
다음를 허용하도록 경로를 조정해야 html, xml, json 등 다양한 요청 형식에 일반적으로 응답하는 방식입니다. – railsdog
@railsdog이 코드를 제 코드에 추가했습니다. if @ contacts.save respond_to do | format | format.json {render : json => @ result.to_json} end else render "new" end' 그러나 이것은 작동하지 않습니다. 그것은 어떤 오류라도 보여주지 않습니다. – 2619
AJAX 요청이'contacts' 컨트롤러의'contacts' 액션을 치려고 애 쓰고 있다고 생각합니다. 라우팅에 관한 레일 가이드를 살펴 보는 것이 가치 있다고 생각합니다. - http://guides.rubyonrails.org/routing.html – mylescarrick