// Create XHR object var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } else { throw new Error("Ajax is not supported by this browser"); } function ready() { alert("Start..... ."); // Handle asynchronous requests through events xhr.onreadystatechange = function() { if( xhr.readyState == 4 ) { alert( "Ready."); if( xhr.status == 200 ) { alert("Successfully obtained the result returned by the server."); // After the request is completed, the server can be obtained Returned content alert( xhr.responseText ); // Get the json object returned by the server var alice = eval( "(" xhr.responseText ")" ); alert( alice. name ); } } }; //Set request parameters xhr.open("get", "data.json" ); xhr.send( null ); }
jQuery simply wraps the use of the xhr object, by adding common access methods to the jQuery object, and then providing it to the jQuery object for use.
// The main extension is in jQuery.ajax. jQuery.extend({ // #6299 // Default parameters for requests ajaxSettings: { url: location.href, type: "GET", contentType: "application/x-www-form-urlencoded", data: null, xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function () { return new window.XMLHttpRequest(); } : function () { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } }, // Used to set jQuery.ajaxSettings and set the request parameters ajaxSetup: function (settings) { jQuery. extend(jQuery.ajaxSettings, settings); }, ajax: function (origSettings) { // Actual ajax function var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings ); // Create xhr object xhr = s.xhr(); // Callback function var onreadystatechange = xhr.onreadystatechange = function (isTimeout) { if (xhr. readyState === 4) { if (xhr.status == 200) { s.success.call(origSettings, xhr.responseText); } } }; //Set request parameters xhr.open(s.type, s.url); // Send the data to make a request xhr.send(s.data); // return XMLHttpRequest to allow aborting the request etc. return xhr; }, // Use the get method to issue an ajax request get: function (url, data, callback, type) { // shift arguments if data argument was omitted if (jQuery.isFunction(data)) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }
}); // #6922 // Extend the jQuery object and add the load method jQuery.fn.extend( { load: function (url) { var self = this; jQuery.get(url, function (data) { self.each(function () { this.innerHTML = data; } ) } ) } } )