1

私はRailsに取り組んでおり、ajaxポストデータ呼び出しに問題があります。それは機能しており、データはdbに入力されていますが、成功機能のアラート機能が起動していないため、SUCCESS機能は機能していません。

さらに、ページ全体を更新せずに投稿にコメントを追加したい。

AJAX コードは次のようになります。

<script type="text/javascript">
$(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);
            }
        });
    });
});
</script>

コントローラーコードは次のとおりです。

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 関数にデータを投稿するのに問題なく機能します。しかし、「成功」時にアラート機能のデータを返したいのですが、成功機能のアラートが機能せず、エラー機能のアラートが発火しています。

4

1 に答える 1

1

試す:

 $('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の結果を確認し、ここに貼り付けます。

于 2013-06-19T12:43:59.757 に答える