如何将json响应传递回客户端
在我的ruby on rails代码中,我想将json响应发送回客户端。 由于我是新手上的ruby,我不知道我该怎么做。 我想发送error = 1 and success = 0
作为json数据,如果数据没有保存到数据库,如果它成功保存它应该发送success = 1 and error = 0
请参阅下面的代码
这是我的控制器
class ContactsController @result.to_json } end else render "new" end end end
这是我的javascript代码
$('.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); } }); });
还有很多其他优雅的方式,但这是正确的:
class ContactsController < ApplicationController def contacts @contacts = Contact.new(params[:contact]) if @contacts.save render :json => { :error => 0, :success => 1 } else render :json => { :error => 1, :success => 0 } end end end
添加一条到routes.rb的路由。 如果您需要使用html响应,则必须包含respond_to do | format |。
您必须调整路线以接受json数据
match 'yoururl' => "contacts#contacts", :format => :json
然后它会工作