[英]When building a custom ajax form in Rails, what is the proper data to send to to the controller to get it to respond to Json?
I want to build a custom ajax form (not interested in using the Rails out of the box solution): 我想构建一个自定义的ajax表单(对使用Rails开箱即用的解决方案不感兴趣):
$('form.ajaxForm').submit(function(e){
e.preventDefault();
var $form = $(this),
formValues = getFormValues($form),
formUrl = $form.attr('action');
$.post(formUrl, {
data : formValues,
contentType: "application/json",
success : function(data, textStatus, jqXHR){
// do success here
}
});
});
var getFormValues = function($form){
var values = {};
var valuesArray = $form.serializeArray();
for(var i = 0, max = valuesArray.length; i < max; i++){
var value = valuesArray[i];
values[value.name] = value.value
};
return values;
};
I do want to use Rails 3's ability to respond differently when it receives a json request such as: 我确实想利用Rails 3的能力在收到json请求时做出不同的响应,例如:
def create
@registration = Registration.new(params[:registration])
respond_to do |format|
format.html { render action: "new" }
format.json { render json: @registration.errors, status: :unprocessable_entity }
end
end
For some reason, Rails cant process my request during the post, and doesn't respond to json. 由于某些原因,Rails无法在发布期间处理我的请求,并且不响应json。 What in the http headers tells it to respond to json, and what is the proper way to post this data? http标头中的内容告诉它响应json,并且发布此数据的正确方法是什么?
Looking at the Rails API docs I came across this tidbit: 在查看Rails API文档时,我遇到了这个提示:
Rails determines the desired response format from the HTTP Accept header submitted by the client. Rails从客户端提交的HTTP Accept标头中确定所需的响应格式。
jQuery's $.ajax
call has an accepts
setting that can be used to set the value for this header but I believe that using dataType
will automatically configure this for you. jQuery的$.ajax
调用具有一个accepts
设置,可用于设置此标头的值,但我相信使用dataType
会自动为您配置此值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.