How to use the data retrieved from ajax?

Whenever you want to use the data retrieved from ajax, you must use it in the callback function which is triggered when the ajax call receives the response.  This is a common practice.

 

But if the ajax call to retrieve data resides in a common function, it would be a little more complicated. Below I give an example to explain this.

 

function DataUtil(callBack) {
	var me = this;
	$.ajax({
		url : "../json/test.json",
		success : function(data) {
			me.data = $.parseJSON(data);
			callBack(me);
		}
	});

	// can only be used in the callBack
	me.getName = function() {
		return me.data.name;
	};

	// can only be used in the callBack
	me.getDescription = function() {
		return me.data.description;
	};
}

function displayRetrievedData() {
	var dataRetrieved = {};
	var callBack = function(dataUtil) {
		dataRetrieved.name = dataUtil.getName();
		dataRetrieved.description = dataUtil.getDescription();
		console.log("in the call back:");
		console.log(dataRetrieved);// gets the correct data from the json
	};
	DataUtil(callBack);
	console.log("out the call back:");
	console.log(dataRetrieved);// not sure it gets the data from the json. It
								// depends the ajax call speed
}

function canNotGetCorrectData() {
	var dataRetrieved = {};
	var dataUtil = new DataUtil(function() {
	});
	dataRetrieved.name = dataUtil.getName();// not sure the data is ready
	dataRetrieved.description = dataUtil.getDescription();// not sure the data is ready
	console.log("Can not get the data:");
	console.log(dataRetrieved);
}

displayRetrievedData();
canNotGetCorrectData();
 

 

 

你可能感兴趣的:(Ajax)