You can only access data from an AJAX request in a callback:
window.onload=LoadData("Home", {}); var _doc = {}; function LoadData(page, params) { $.get(page, params, function ( data ) { _doc = jQuery.parseJSON( data ); document.title = _doc.Title.Title; } )); };
AJAX requests ( Asynchronous JavaScript and XML) requests are asynchronous; the browser initiates the request, rather than waiting for a response ... instead, JavaScript execution continues. Some time later, when the HTTP request for the AJAX request is completed, the callback you provided for the AJAX request is called and has access to the data contained in the HTTP response.
In your situation document.title = _doc.Title.Title; It is executed immediately after sending the AJAX request (i.e., before it happened some time later , as mentioned above); therefore the callback _doc = jQuery.parseJSON( data ); is not running yet, so _doc is still an empty object, so _doc.Title is undefined, and trying to get Title in undefined _doc.Title is an error.
Not related to your problem, but FYI, you can look at the jQuery.getJSON method; the difference between the jQuery.get method is that the response object you passed in will already be a JSON object (so you wonβt need to call jQuery.parseJSON ).
source share