我正在“ajax”我的 Rails Web 应用程序,这是我以前从未做过的事情。我的目标是在不刷新页面的情况下将产品添加到数据库
我有一个用户和产品 Controller 。用户在其个人页面中添加了产品。但我收到了 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'.
产品 Controller 代码:
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
用户 Controller ,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'
})
});
无论如何,您应该设置一些要发送的参数,否则您的 Controller 将在允许的情况下创建一个空产品,或者如果您对模型进行了一些验证,则将返回 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。 (Source)
$.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()
关于javascript - 错误请求,错误 URI 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20379689/