load.js 1.8 KB

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