Manipulation: Support $el.html(selfRemovingScript) (#5378)
[jquery.git] / src / ajax / load.js
blob044dc09ddec6f9064edbf044e801bcf77bfeffe5
1 import { jQuery } from "../core.js";
2 import { stripAndCollapse } from "../core/stripAndCollapse.js";
4 import "../core/parseHTML.js";
5 import "../ajax.js";
6 import "../traversing.js";
7 import "../manipulation.js";
8 import "../selector.js";
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( " " );
18         if ( off > -1 ) {
19                 selector = stripAndCollapse( url.slice( off ) );
20                 url = url.slice( 0, off );
21         }
23         // If it's a function
24         if ( typeof params === "function" ) {
26                 // We assume that it's the callback
27                 callback = params;
28                 params = undefined;
30         // Otherwise, build a param string
31         } else if ( params && typeof params === "object" ) {
32                 type = "POST";
33         }
35         // If we have elements to modify, make the request
36         if ( self.length > 0 ) {
37                 jQuery.ajax( {
38                         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 ) {
48                         // Save response for use in complete callback
49                         response = arguments;
51                         self.html( selector ?
53                                 // If a selector was specified, locate the right elements in a dummy div
54                                 // Exclude scripts to avoid IE 'Permission Denied' errors
55                                 jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
57                                 // Otherwise use the full result
58                                 responseText );
60                 // If the request succeeds, this function gets "data", "status", "jqXHR"
61                 // but they are ignored because response was set above.
62                 // If it fails, this function gets "jqXHR", "status", "error"
63                 } ).always( callback && function( jqXHR, status ) {
64                         self.each( function() {
65                                 callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
66                         } );
67                 } );
68         }
70         return this;