load.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. define( [
  2. "../core",
  3. "../core/parseHTML",
  4. "../ajax",
  5. "../traversing",
  6. "../manipulation",
  7. "../selector",
  8. // Optional event/alias dependency
  9. "../event/alias"
  10. ], function( jQuery ) {
  11. // Keep a copy of the old load method
  12. var _load = jQuery.fn.load;
  13. /**
  14. * Load a url into a page
  15. */
  16. jQuery.fn.load = function( url, params, callback ) {
  17. if ( typeof url !== "string" && _load ) {
  18. return _load.apply( this, arguments );
  19. }
  20. var selector, type, response,
  21. self = this,
  22. off = url.indexOf( " " );
  23. if ( off > -1 ) {
  24. selector = jQuery.trim( url.slice( off ) );
  25. url = url.slice( 0, off );
  26. }
  27. // If it's a function
  28. if ( jQuery.isFunction( params ) ) {
  29. // We assume that it's the callback
  30. callback = params;
  31. params = undefined;
  32. // Otherwise, build a param string
  33. } else if ( params && typeof params === "object" ) {
  34. type = "POST";
  35. }
  36. // If we have elements to modify, make the request
  37. if ( self.length > 0 ) {
  38. jQuery.ajax( {
  39. url: url,
  40. // If "type" variable is undefined, then "GET" method will be used.
  41. // Make value of this field explicit since
  42. // user can override it through ajaxSetup method
  43. type: type || "GET",
  44. dataType: "html",
  45. data: params
  46. } ).done( function( responseText ) {
  47. // Save response for use in complete callback
  48. response = arguments;
  49. self.html( selector ?
  50. // If a selector was specified, locate the right elements in a dummy div
  51. // Exclude scripts to avoid IE 'Permission Denied' errors
  52. jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
  53. // Otherwise use the full result
  54. responseText );
  55. // If the request succeeds, this function gets "data", "status", "jqXHR"
  56. // but they are ignored because response was set above.
  57. // If it fails, this function gets "jqXHR", "status", "error"
  58. } ).always( callback && function( jqXHR, status ) {
  59. self.each( function() {
  60. callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
  61. } );
  62. } );
  63. }
  64. return this;
  65. };
  66. } );