load.js 1.8 KB

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