I have an Ajax form with a data-remote="true"
attribute which I'm submitting to a controller in rails.
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.
Something like this:
$("#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?
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.leng开发者_如何学Cth;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
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.
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.
As of the jQuery 1.5, there is a local beforeSend callback that can be bound to your request. Documentation link and another documentation link
EDIT: The request data is available in the jqXHR object, the first parameter beforeSend callback.
beforeSend(jqXHR, settings)
Try inspecting the jqXHR object in firebug to see exactly where it stores the POST data and just append your values,
To change data
attribute (at least now, using Jquery 1.7.2) inside the beforeSend
method (the Jquery native method), you can just alter the this.data
variable.
精彩评论