JQuery AJAX 在 GET 请求完成时返回 XML

JQuery AJAX return XML on GET request complete

本文关键字:完成时 返回 XML 请求 GET AJAX JQuery      更新时间:2023-09-26

一旦我的XML文件(或对象)成功返回,我需要执行代码。以前没有,也没有重复;文件返回仅一次。

我的代码是否已经完成了我想要完成的任务?它似乎在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
          });
    })();
});

我知道有onerror代码和readystatechange值可以检查和验证......我是否应该在轮询服务器以查找 XML 文件时检查这些值?

删除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
          });
});

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

由于@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部分中这样做会更有意义。