0
我是Rails的新手,正在嘗試使用jQuery.post使用ajax發佈表單並顯示結果。使用jQuery.post時發生400個錯誤的請求錯誤
POST http://localhost:3000/main/newStuff 400 (Bad Request)
我在看的例子在this jQuery page底部:
但我在我的控制檯,當我點擊提交只得到這一點。
這裏是我的Ajax代碼:
$("#new_stuff_form").submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $(this),
title = $form.find("#new_stuff_title").val(),
url = $form.attr("action");
// Send the data using post
var posting = $.post(url, { title: title });
posting.done(function(data) {
console.log(data);
});
posting.fail(function(data) {
console.log(data);
});
});
這裏是我的控制器:
def createStuff
@stuff = Stuff.new(stuff_params)
@stuff.save
render json: {status: "ok"}
end
private
def stuff_params
params.require(:stuff).permit(:title, :due_date)
end
這是我的觀點:
<%= simple_form_for @stuff, url: stuff_create_path, html: {id: "new_stuff_form",class: "form-horizontal", role: "form"} do |f| %>
<div class="form-group">
<label for="new_stuff_title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<%= f.input_field :title, class: 'form-control', id: 'new_stuff_title' %>
</div>
</div>
<%= f.button :submit %>
這裏是我的路線設置:
post 'main/newStuff' => 'main#createStuff', as: :stuff_create
P.S.它工作時,我不使用ajax,所以我認爲控制器和視圖是好的。
你能設置這個'console.log' url和title變量來確保它們是正確的嗎? – 2014-09-05 18:32:38
Hi @MohamedYakot,是的,我添加了console.log(url)和console.log(標題)到我的代碼和輸出是「/ main/newStuff」和正確的字符串我輸入到「標題」的形式。 – czphilip 2014-09-05 18:50:09
我看到你的動作叫'createStuff',而不是'newStuff',你忘了改它嗎?如果沒有請輸入'newStuff'動作 – 2014-09-05 18:57:28