我有两个 js 文件。一个是route.js
,第二个是xml.js
。在route.js
文件中,我正在调用一个位于xml.js
. 该函数的作用是通过 xml 链接解析并返回 xml 对象。当我console.log($(xml))
在 xml.js 内部执行时,它会显示 xml,但是当我返回此对象并在console.log(Xml.init(param, param, param))
内部执行时route.js
,它会返回undefined
. 为什么?
这是我的代码
路由.js
var Route = {
fromurl : null,
tourl : null,
from : null,
to : null,
init: function (fromaddress, toaddress) {
from = fromaddress;
to = toaddress;
fromurl = 'http://example.com/url=' + fromurl;
tourl = 'http://example.com/url=' + tourl;
Route.searchRoute();
},
searchRoute: function () {
console.log(Xml.init(from, to, fromurl)); // <---- this returns undefined why
}
};
xml.js
var Xml = {
to : null,
from : null,
url : null,
init: function (fromaddress, toaddress, link) {
from = fromaddress;
to = toaddress;
url = link;
this.requestXml();
},
requestXml: function () {
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: this.parseXml
});
},
parseXml: function (xml) {
console.log($(xml)); //<--- works absolutely fine here
return $(xml);
}
};
更新
我也将 Xml 对象更改为跟随。在这里,我正在转换xml
为string
然后将字符串转换为json
使用[xmltojson][1]
插件,但它仍然返回未定义。请帮助我如何解决这个问题?
var Xml = {
to : null,
from : null,
url : null,
requestXml: function (fromaddress, toaddress, link) {
from = fromaddress;
to = toaddress;
url = link;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: function (xml) {
var xmltostring = Xml.xmlToString(xml),
stringtojson = Xml.stringxmlToJson(xmltostring);
return stringtojson;
}
});
},
xmlToString: function (xmlData) {
var xmlString;
if (window.ActiveXObject) {
xmlString = xmlData.xml;
} else {
xmlString = (new XMLSerializer()).serializeToString(xmlData);
}
return xmlString;
},
stringxmlToJson: function (stringxml) {
return $.xml2json(stringxml);
}
};