0

I need to execute code once my XML file (or object) has been returned successfully. Not before, and not repeatedly; just one time after the file has been returned.

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.

$(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?

4

2 回答 2

1

后去掉逗号async: true

此外,如果您不打算再次调用,您的 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
          });
});
于 2012-08-16T13:59:10.663 回答
0

这是原始提问者作为编辑添加的,我已将其转换为社区 wiki 答案,因为它应该是答案,而不是编辑。

感谢@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
        });
    })();
});

最后一条评论,您应该能够更改setTimeout(GetFile, 5000)setInterval(GetFile, 5000),然后它将不断轮询您的 XML 文件。但是,在本success节中这样做会更有意义。

于 2015-06-23T15:34:25.103 回答