我创建了一个JavaScript对象,并且我试图从中获取SOM数据。我使用jQuery Ajax获取发送一些值,然后从PHP脚本中重新保留它们。这有效,但是当我尝试使用javaScript对象的一个键来消除我获得的"未定义"的值。
对象:
var getDBresults = (function () {
function getResult(url,TableName ,callback){
$.ajax({
url: url,
type: 'POST',
data: {
'table':TableName,
},
success: function(data){
callback(data);
},
error: function(event){
alert(event.error);
}
});
}
return {
getAllVideoes: function(){
getResult("getAllResults.php", "videoer", function(data){
console.log(data); //Works
return data;
});
},
}
})();
在我的其他脚本中:
var obj = getDBresults;
var data = obj.getAllVideoes(); //this runs, and produce the log showed above
console.log(data) //results in undefined
console.log(obj.getAllVideoes()) //results in undefined
也许您可以使用回调,它将解决您的异步问题:http://recurial.com/programming/understanding-callback-functions-functions-in-javascript/p>>