我想通過單擊按鈕觸發使用AJAX創建模型。我在我的控制器中定義的create
動作和按鈕添加一個onClick事件監聽器:Ajax調用來創建一個模型的onClick實例(Rails 4)
<a class="add-step btn btn-primary">Add</a>
<script>
$('.add-step').click(function(){
console.log("button works");
$.ajax({
type:'POST',
url: '/blocks',
dataType: "son",
contentType: "application/json; charset=utf-8",
data: { content: "hello" }
});
});
</script>
在我blocks_controller.rb
:
def create
@block = Block.new(blocks_params)
respond_to do |format|
if @block.save
format.json { render json: @block }
else
format.html { render action: "new" }
format.json { render json: @block.errors }
end
end
end
private
def blocks_params
params.require(:blocks).permit(:content)
end
我在控制檯中看到「按鈕的作品」,但我也有一個錯誤:
POST http://localhost:3000/blocks 400 (Bad Request)
這似乎是與PARAMS的問題(因爲我沒有得到一個404,它好像create
行動「工程」),但我找不到有什麼問題。
針對類似問題進行了研究? – Nithin
@Nithin我做了,發現這個職位:http://stackoverflow.com/questions/20888250/ruby-rails-structuring-data-for-ajax-call-to-controller-action但即使它的網址似乎錯了,因爲POST請求必須對/模型,而不是/模型/創建,它沒有一個非常有用的答案 –
檢查http://stackoverflow.com/a/4157037/2231236 – Nithin