jquery - jsonp overwrite callback get parameter
I'm writing a dynamic js that should send a request to an action, that is defined in the href attribute in a link.
The link look like that:
<a href="module/action?callback=MyCallback">show something</a>
As you can see the link has a get param named callback. That is defined, because the request method should be as generic as possible and the element should know by itself, what it has to do with the response.
Now i send the request with jquery ajax function to the action, looking like that:
jQuery('#mylink').live("click", function() { jQuery.ajax({ type: 'GET', dataType:"jsonp", error: ErrorHandler.catchXhrError, url: jQuery('#mylink').attr('href'); }); });
That works very well, in principle. But my problem is, that jquery defines its own callback get param and i don't know, how i can tell the method, that the callback param in my links href is the right one and the request-uri is looking like that:
http:/example.com/module/action?callback=MyCallback&cal开发者_如何学编程lback=jsonp1279196981233
The only way out i see, is to define my own callback-param named mycallback and interpret mycallback in the action instead of callback:
<a href="module/action?callback=MyCallback">show something</a>
But i don't like this solution, because my request uri has a param that will not be used:
http:/example.com/module/action?mycallback=MyCallback&callback=jsonp1279196981233
Please attend, that i could not define the name of the callback method inside the ajax method
jQuery('#mylink').live("click", function() { jQuery.ajax({ type: 'GET', dataType:"jsonp", jsonpCallback: 'MyCallback', error: ErrorHandler.catchXhrError, url: jQuery('#mylink').attr('href'); }); });
because the send Method should be generic and will be used across our whole side and the response has to be processed in many different ways by different js methods.
Hope i could describe my problem sufficiently and would be happy about any help.
You should use the jQuery.ajax
version but not hardcode the callback name. Instead parse the href attribute and extract the name of the callback to use..
and here is the parsing..
jQuery('#mylink').live("click", function() {
var href = jQuery('#mylink').attr('href');
jQuery.ajax({
type: 'GET',
dataType:"jsonp",
jsonpCallback: href.match(/([?&]callback[a-zA-Z0-9=]+)/)[0].split('=')[1],
error: ErrorHandler.catchXhrError,
url: href;
});
});
Have you looked into http://code.google.com/p/jquery-jsonp/ ?
精彩评论