我正在对XML文件执行Ajax请求并将XML映射到JavaScript对象我的问题是记录对象并查看我赢得的值但是当我尝试返回值时,我不断得到undefined
,即使所有代码都在AJAX请求的成功回调中,我的代码如下:
// Errors Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
// Ajax Request
$.ajax({
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
$(xml).find('EcaAdminBc').each(function () {
var code = $(this).find('code').text();
var msg = $(this).find('msg').text();
ErrorsObject[code] = msg;
});
// Reformat Errors
if(ErrorApplet.length > 0) {
$(ErrorApplet).each(function(){
var Error = $(this).text();
if(Error.indexOf("SBL") >= 0){
var ErrorCode = Error.split('(')[1].replace(")","");
var ErrorText = ErrorsObject[ErrorCode];
// The Log is showing the values correctly but i cant access the object values
console.log(ErrorsObject);
// ErrorText And ErrorCode Are always undefined !!
if(typeof ErrorText != 'undefined'){
$(this).text(ErrorText);
}
}
});
}
}
});
答案 0 :(得分:0)
我需要额外的上下文,但我想问题是什么。你正试图做这样的事情:
var myFunction = function(){
// Error Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
$.ajax(
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
//using response to fill ErrorsObject
ErrorsObject['Ok'] = 'This key has Value!';
//more awesome code here
//... lets check again:
console.log(ErrorsObject['OK']); //Outputs 'This key has Value!'
}
);
return ErrorsObject;
};
var myAwesomeErrorObject = myFunction();
console.log(myAwesomeErrorObject['OK']); //undefined!
console.log(myAwesomeErrorObject); //Empty object!
问题是myFunction
在成功回调函数执行之前完成了(回调是异步)。这就是记录myAwesomeErrorObject['OK']
显示undefined
的原因。我想你也在成功回调中尝试了return ErrorsObject
,但这也行不通。
为了修复您的代码,您必须:
myfunction
并从成功回调中执行。