Rails,Ajax,Post Function,Jquery

我正在研究Rails并且遇到ajax post数据调用的问题。 它正在工作,数据输入db但SUCCESSfunction不起作用,因为成功函数中的警报function未触发。

此外,我想在不刷新整个页面的情况下为我的post添加评论。

AJAX代码如下所示:

 $(document).ready(function () { $('form').submit(function () { $.ajax({ url: '/comments/create', type: "POST", dataType: 'json', processData: false, success: function (msg) { alert(msg); }, error: function (xhr, status) { alert(xhr.error); } }); }); });  

和控制器代码是:

 def create puts 'params', params.inspect @post = Post.find(params[:post_id]) @comment = @post.comments.new(params[:comment]) respond_to do |format| if @comment.save format.html { redirect_to(@post, :notice => 'Thanks for comment.') } format.json { render json => @post, :msg=>"comment oK" } else format.html { render :action => "new" } format.json { render :xml => @comment.errors, :msg=>"comment oooK", :status => :unprocessable_entity } end end end 

此代码可以很好地将数据发布到create函数,该函数创建(发布?)db的条目。 但是我希望在“成功”时返回警报function中的数据,但是成功function中的警报不起作用,并且错误function中的警报正在触发。

尝试:

  $('form').submit(function() { var myForm = $('form').serialize(); $.ajax ({ url:'/comments/create', type:"POST", dataType:'json', data: myForm, processData:false, success: function (msg) { alert(msg); }, error: function (xhr, status) { alert(xhr.error); } }); }); 

如果这不起作用,请在AJAX请求中写下您通过网络发送的内容。 使用Chrome控制台或Firebug在此处检查并粘贴POST结果。