javascript JQuery AJAX 在 GET 请求上返回 XML 完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11988780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery AJAX return XML on GET request complete
提问by Shrout1
I need to execute code once my XML file (or object) has been returned successfully. Not before, and not repeatedly; just one time afterthe file has been returned.
一旦我的 XML 文件(或对象)成功返回,我就需要执行代码。不是以前,也不是重复;只是一个时间后,该文件已被退回。
Does my code already do what I am trying to accomplish? It seems to have failed a couple of times in IE and I need to be sure that it is reliable.
我的代码是否已经完成了我想要完成的任务?它似乎在 IE 中失败了几次,我需要确保它是可靠的。
$(document).ready(function(){
(function GetFile(){
$.ajax({
type: "GET",
url: "Produce.xml",
dataType: "xml",
cache: false,
success: function(result) {
alert("XML File is loaded!");
alert(result);
},
async: true
});
})();
});
I know that there are onerror
codes and readystatechange
values that can be checked and verified... Should I be checking these values while polling the server for the XML file?
我知道有可以检查和验证的onerror
代码和readystatechange
值......我应该在轮询服务器以获取 XML 文件时检查这些值吗?
回答by
remove comma after async: true
后面去掉逗号 async: true
Also, your GetFile function will execute immediately if you're not planning on calling again then might as well go with anonymous or remove that function all together
此外,如果您不打算再次调用,您的 GetFile 函数将立即执行,然后最好使用匿名或一起删除该函数
$(document).ready(function(){
$.ajax({
type: "GET",
url: "Produce.xml",
dataType: "xml",
cache: false,
success: function(result) {
alert("XML File is loaded!");
alert(result);
},
async: true
});
});
回答by durron597
This was added as an edit by the original asker, I have converted it to a community wiki answer because it should be an answer, not an edit.
这是原始提问者作为编辑添加的,我已将其转换为社区 wiki 答案,因为它应该是答案,而不是编辑。
Fixed it thanks to @AndrewDouglas suggestion and here is the new code (which works great):
感谢@AndrewDouglas 的建议修复了它,这是新代码(效果很好):
$(document).ready(function(){
(function GetFile(){
$.ajax({
type: "GET",
url: "Produce.xml",
dataType: "xml",
cache: false,
success: function(result) {
alert("XML File is loaded!");
alert(result);
},
error:function (xhr, ajaxOptions, thrownError){
z++;
alert(xhr.status);
alert(thrownError);
setTimeout(GetFile, 5000);
console.log("Error " +z+": " + thrownError);
},
async: true
});
})();
});
One final comment, you should be able to change setTimeout(GetFile, 5000)
to setInterval(GetFile, 5000)
and then it will continually poll your XML file. Doing that in the success
section would make a bit more sense, however.
最后一个评论,您应该能够更改setTimeout(GetFile, 5000)
为setInterval(GetFile, 5000)
,然后它将不断轮询您的 XML 文件。但是,在本success
节中这样做会更有意义。