[英]Bad Request, bad URI 400 Error
我正在“整理”我的Rails Web應用程序,這是我以前從未做過的事情。 我的目標是在不刷新頁面的情況下將產品添加到數據庫
我有一個用戶和產品控制器。 用戶在其個人頁面中添加了產品。 但是我遇到了400錯誤。
Bad Request
bad URI `/users/function (options) { return Utils.build_path([], ["format"],[2,[2,[7,"/",false],[6,"products",false]],[1,[2,[8,".",false],[3,"format",false]],false]], arguments); }'.
並且
bad URI `/users/function%20(options)%20%7B%20%20return%20Utils.build_path([],%20[%22format%22],%20[2,[2,[7,%22/%22,false],[6,%22products%22,false]],[1,[2,[8,%22.%22,false],[3,%22format%22,false]],false]],%20arguments);%20%20%7D'.
產品控制器代碼:
class ProductsController < ApplicationController
respond_to :html, :json
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html do
redirect_to '/'
end
format.json { render json: @product.to_json }
else
# Add a handler for unsuccessful cases
end
end
end
def product_params
params.require(:product).permit(:title, :units)
end
end
用戶控制器的show方法:
def show
@user = User.find(params[:id])
@product = Product.new
end
具有ajax功能的jQuery函數:
$('.edit-box > form input[type=submit]').click(function(e) {
closeEdit();
event.preventDefault();
$.ajax({
url: Routes.products_path,
dataType: 'json',
type: 'POST'
})
});
有任何想法嗎?
Routes.product_path
是一個javascript函數,因此您需要使用方括號將其調用。 如果不調用它,則將功能代碼作為ajax調用的url,這就是為什么會收到BAD URI錯誤的原因。
嘗試:
$('.edit-box > form input[type=submit]').click(function(e) {
closeEdit();
event.preventDefault();
$.ajax({
url: Routes.products_path(),
dataType: 'json',
type: 'POST'
})
});
無論如何,您應該設置一些要發送的參數,否則,如果您對模型進行了一些驗證,則控制器將創建一個空產品(如果允許),否則將返回500錯誤 。
要發送參數,請使用data
選項。 (此處的文檔: http : //api.jquery.com/jQuery.ajax )
$('.edit-box > form input[type=submit]').click(function(e) {
closeEdit();
event.preventDefault();
$.ajax({
url: Routes.products_path(),
dataType: 'json',
type: 'POST',
data: {key1: "value1", key2: "value2", ... }
})
});
要獲取值,您可以在表單上使用serializeArray()
jQuery方法,但是您將獲得一個對象數組,其中包含表單輸入的name
和value
。 如果您想要一個普通對象,則可以輕松地將serializeObject()
方法添加到jQuery。 ( 來源 )
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
/* Now you can use the method to serialize your form to an object */
var dataToSend = $('.edit-box > form').serializeObject()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.