如何在Rails中将数据追加到jquery-ujs发布请求? [英] How do I append data to a jquery-ujs post request in Rails?
问题描述
我有一个带有data-remote="true"
属性的Ajax表单,该表单正在Rails中提交给控制器.
I have an Ajax form with a data-remote="true"
attribute which I'm submitting to a controller in rails.
我想做的是使用 jquery-ujs 事件系统,以便在数据发送到服务器之前将其附加到请求中.
What I'd like to do is to use the jquery-ujs event system to append data to the request before it gets sent to the server.
类似这样的东西:
$("#my_form").bind('ajax:beforeSend', function(xhr, settings){
// serialize some object and append it
});
我不知道如何在数据上进行实际标记?
I can't figure out how to actually tag on the data though?
编辑,这就是控制台中"xhr"对象的外观.
Edit This is what the 'xhr' object looks like in the console.
f.Event
currentTarget: DOMWindow
data: undefined
exclusive: undefined
handleObj: Object
handler: function N(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(y,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}
jQuery16103879226385615766: true
liveFired: HTMLDocument
namespace: ""
namespace_re: /(^|\.)(\.|$)/
result: undefined
target: HTMLFormElement
timeStamp: 1306788242911
type: "ajax:beforeSend"
__proto__: Object
推荐答案
最后我自己弄明白了这一点.看来,尽管 docs 说了什么,但ajax:beforeSend
钩子实际上接受了三个参数.根据这篇有用的博客文章,它们是event
,xhr
和settings
按此顺序.
I figured this one out myself in the end. It appears that despite what the docs say, the ajax:beforeSend
hook actually takes three arguments. According to this helpful blog post they are event
, xhr
and settings
in that order.
我要查找的表单数据在settings
参数的data
属性中.
The form data I was looking for is in the in the data
attribute of the settings
argument.
所以基本上,我现在可以使用函数将数据添加到请求中
So basically, I can now add data to the request with the function
$("#my_form").bind('ajax:beforeSend', function(event, xhr, settings){
settings.data += "&serialized=data";
});
其他参数将在服务器上可用.
And the extra paramaters will be available on the server.
这篇关于如何在Rails中将数据追加到jquery-ujs发布请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!