首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Ajax >

How to use the data retrieved from ajax

2012-09-08 
How to use the data retrieved from ajax?Whenever you want to use the data retrieved from ajax, you

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 callBackme.getName = function() {return me.data.name;};// can only be used in the callBackme.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 readydataRetrieved.description = dataUtil.getDescription();// not sure the data is readyconsole.log("Can not get the data:");console.log(dataRetrieved);}displayRetrievedData();canNotGetCorrectData();
?

?

?

热点排行