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