jsonp.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. define([
  2. "../core",
  3. "./var/nonce",
  4. "./var/rquery",
  5. "../ajax"
  6. ], function( jQuery, nonce, rquery ) {
  7. var oldCallbacks = [],
  8. rjsonp = /(=)\?(?=&|$)|\?\?/;
  9. // Default jsonp settings
  10. jQuery.ajaxSetup({
  11. jsonp: "callback",
  12. jsonpCallback: function() {
  13. var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
  14. this[ callback ] = true;
  15. return callback;
  16. }
  17. });
  18. // Detect, normalize options and install callbacks for jsonp requests
  19. jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
  20. var callbackName, overwritten, responseContainer,
  21. jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
  22. "url" :
  23. typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
  24. );
  25. // Handle iff the expected data type is "jsonp" or we have a parameter to set
  26. if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
  27. // Get callback name, remembering preexisting value associated with it
  28. callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
  29. s.jsonpCallback() :
  30. s.jsonpCallback;
  31. // Insert callback into url or form data
  32. if ( jsonProp ) {
  33. s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
  34. } else if ( s.jsonp !== false ) {
  35. s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
  36. }
  37. // Use data converter to retrieve json after script execution
  38. s.converters["script json"] = function() {
  39. if ( !responseContainer ) {
  40. jQuery.error( callbackName + " was not called" );
  41. }
  42. return responseContainer[ 0 ];
  43. };
  44. // force json dataType
  45. s.dataTypes[ 0 ] = "json";
  46. // Install callback
  47. overwritten = window[ callbackName ];
  48. window[ callbackName ] = function() {
  49. responseContainer = arguments;
  50. };
  51. // Clean-up function (fires after converters)
  52. jqXHR.always(function() {
  53. // Restore preexisting value
  54. window[ callbackName ] = overwritten;
  55. // Save back as free
  56. if ( s[ callbackName ] ) {
  57. // make sure that re-using the options doesn't screw things around
  58. s.jsonpCallback = originalSettings.jsonpCallback;
  59. // save the callback name for future use
  60. oldCallbacks.push( callbackName );
  61. }
  62. // Call if it was a function and we have a response
  63. if ( responseContainer && jQuery.isFunction( overwritten ) ) {
  64. overwritten( responseContainer[ 0 ] );
  65. }
  66. responseContainer = overwritten = undefined;
  67. });
  68. // Delegate to script
  69. return "script";
  70. }
  71. });
  72. });