我有一个从系统上的XML文件中提取信息的函数。然后,它将提取位于该文件中的值,并将它们放入数组中。一旦函数被调用,值就进入数组,但是一旦函数结束,这些值就会消失。
function getXML(location,day){
$(document).ready(function () {
$.ajax({
type:'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain:true,
url: './../CurrentFiles/'+ location +'.xml', // name of file you want to parse
success: function (xmldata){
if(array[0] == null){
$(xmldata).find('dgauges').children().each(function(){
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
});
return array[day];
}据我所研究,这可能是异步的一个问题,但我不完全明白这是什么。而且,我对jquery非常陌生,所以如果有什么不对劲的地方,那就是原因所在。
THis是我对这个函数的计划
我有一个XML文件格式化如下
<dgages><d>26.850</d><d-1>7.70</d-1><d-2>2.00</d-2><d-3>27.90</d-3></dgages>我试图在数组中提取所有这些值,这样我就可以对它们进行一些计算。
发布于 2015-08-05 12:38:14
尝试进行同步调用。默认情况下,AJAX调用是异步的,这意味着在等待上一行的结果之前,代码将跳转到下一行。您可以通过告诉AJAX调用同步执行该结果来强制执行该结果:
function getXML(location, day) {
var array = [];
$.ajax({
type: 'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain: true,
async: false, // Wait until AJAX call is completed
url: './../CurrentFiles/' + location + '.xml', // name of file you want to parse
success: function(xmldata) {
if (array[0] == null) {
$(xmldata).find('dgauges').children().each(function() {
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
return array[day];
}https://stackoverflow.com/questions/31832624
复制相似问题