我试图在文本区域中创建XML格式的输出,但遇到了异步问题:
$(document).ready(function() {
var geocoder;
geocoder = new google.maps.Geocoder();
$('#xmloutput').val('<?xml version="1.0" encoding="UTF-8"?>\n<parent>\n');
var addresslist = 'one\ntwo\nthree';
var addlines = addresslist.split('\n');
$.each(addlines, function(name, value) {
geocoder.geocode( { 'address': value}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#xmloutput').val($('#xmloutput').val()+'<node>'+value+'</node>\n');
}
});
});
$('#xmloutput').val($('#xmloutput').val()+'</parent>');
});我想要这个输出:
<?xml version="1.0" encoding="UTF-8"?>
<parent>
<node>one</node>
<node>two</node>
<node>three</node>
</parent>但是我得到这个输出是因为地理编码需要一段时间...
<?xml version="1.0" encoding="UTF-8"?>
<parent>
</parent><node>one</node>
<node>two</node>
<node>three</node>我已经看到了很多类似的帖子和修复,看起来是链接或回调,但我还没有设法让任何东西工作。我应该如何处理这个问题?
谢谢!本
发布于 2012-10-21 22:14:11
更改each循环,并在循环的最后一次传递中添加结束标记
/* first argument of `each` for an array is `index` which will increment on each pass*/
$.each(addlines, function(index,value) {
geocoder.geocode({
'address': value
}, function(results,status) {
if (status == google.maps.GeocoderStatus.OK) {
var newString=$('#xmloutput').val() + '<node>' + value + '</node>\n';
/* is this the last item? */
if (index == addlines.length-1) {
newString += '</parent>';
}
$('#xmloutput').val( newString)
}
});
}); 由于服务调用的异步性质,地理编码器仍有可能返回失序的值。如果发生这种情况,您可能需要为所有结果创建一个本地对象,并在加载完整字符串之前使用deffered检查收到的所有结果
发布于 2012-10-21 22:10:10
尝试使用类似以下代码的.append():
$(document).ready(function() {
var geocoder;
geocoder = new google.maps.Geocoder();
$('#xmloutput').val('<?xml version="1.0" encoding="UTF-8"?>\n<parent>\n');
var addresslist = 'one\ntwo\nthree';
var addlines = addresslist.split('\n');
$.each(addlines, function(name, value) {
geocoder.geocode( { 'address': value}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#xmloutput').append('<node>'+value+'</node>\n');
}
});
});
$('#xmloutput').append('</parent>');
});https://stackoverflow.com/questions/12998511
复制相似问题