开发者

Can I add a parameter to a PrototypeJS Ajax request using Ajax.Responder?

I'm trying to secure my AJAX calls by appending a session token (to be matched by a browser cookie by the server) as a parameter to every single AJAX request made from my web app.

I'd like to avoid having to specify the token as an additional parameter in every single Ajax.Updater() request, as that could get onerous very quickly. So I 开发者_如何学运维thought it might be more effective to have this token appended to every request globally, automatically.

I'm wondering whether Ajax.Responder could handle this. It seems as though it should be able to intercept any Ajax request before it's made, and modify the parameters to add the token before it's sent out. But, I have no idea how I'd go about accomplishing it. Would I need to prototype 'Ajax.Responder', and 'burn in' an additional parameter? Or is there an easier way?

My understanding of Ajax.Responder is a little weak, so if somebody could clarify why this would or wouldn't be possible in their answer, it would be greatly appreciated.


I ran into a similar problem, and ended up implementing a simple addParameters() method extension for the Ajax.Request class to get this done for both GET and POST requests.

You can check out the implementation here: https://gist.github.com/3212413.

Feedback welcome!


Prototype sets the parameters array before it calls the Responders callbacks so you can't just add the item you want to the parameters hash. You could append your variables to the url, for example this will add a cache buster random number to every request...

Ajax.Responders.register({
  onCreate: function(o,x) { 
    o.url += (o.url.include('?') ? '&' : '?') + "rnd=" + Math.floor(Math.random()*1000000000);
  }
});


this is how I implemented for a POST request, inspired by Gavin's answer:

Ajax.Responders.register({
    onCreate: function(request) { // add form_key to ajax request
        var formKey = $('form_key');
        var parameters = request.parameters;
        parameters.form_key = formKey.value;
        request.options.postBody = Object.toQueryString(parameters);
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜