【问题标题】:Loop through XML files jQuery循环遍历 XML 文件 jQuery
【发布时间】:2013-04-04 08:39:06
【问题描述】:

我有点被以下问题困扰。

我有几个由 ID 标记的 XML 文件(每个 XML 都由一个值标识)。我现在正在尝试遍历这些文件并将其内容输出到 HTML。

但是它在回调之前开始循环

循环0 循环1 循环2 回调0 回调1 回调2

我需要 循环0 回调0 循环1 回调1

因为我需要在某个时候控制结果。

        var allContent=["xmlfile1","xmlfile2","xmlfile3","xmlfile4"];
        var totalSearch = 0;
        var countSearch = 0;

        function doSearch() {

            var oldContentID = contentID;

            for (iSearch=0;iSearch<allContent.length;iSearch++) {
                totalSearch = totalSearch + countSearch;
                contentID = allContent[iSearch];
                defineContent();

                getXML();

            }
        } 

        function getXML() {
            $.ajax({
                type: "GET",
                url: langFile,
                dataType: "xml",
                beforeSend: function(){

                    $('#results-list').empty();
                    $('#results-list').hide();
                    $('#loading').addClass('loading');
                },
                success: function(xml) {

                    var totalElements;
                    var intSearch = 0;
                    totalSearch = totalSearch + countSearch;
                    countSearch = 0;
                    var searchText = $('#text').val().toLowerCase();

                    totalElements = $(xml).find('news').length;


                    while (intSearch < totalElements) {
                        oFeed = $(xml).find('news:eq('+intSearch+')');
                        var headline = oFeed.find('headline').text();
                        var newsText = oFeed.find('detail').text();
                        var section = oFeed.find('section').text();
                        var category = oFeed.attr('category');

                        var stripEnters = newsText.match(/\r?\n|\r/gi);
                        if (stripEnters != null) {
                            for (var s = 0; s < stripEnters.length ; s++ ){
                                newsText = newsText.replace(stripEnters[s],'');
                            }
                        }

                        var newsText2 = $.htmlClean(newsText, {format:true});
                        var newsText3 = $(newsText2)
                        var newsText4 = $(newsText3).text();
                        var newsText5 = newsText4.replace( /\W/gi, "" );

                        if (section.toLowerCase() == "news" || section.toLowerCase() == "featured") {
                            if (headline.toLowerCase().indexOf(searchText) >= 0) {
                                $('<dt></dt>').html(headline).appendTo('#results-list');
                                $('<dd></dd>').html(newsText).appendTo('#results-list');
                                countSearch++;
                            }//end if
                            else if (newsText5.toLowerCase().indexOf(searchText) >= 0) {
                                $('<dt></dt>').html(headline).appendTo('#results-list');
                                $('<dd></dd>').html(newsText).appendTo('#results-list');
                                countSearch++;
                            }
                        }
                        intSearch++;
                    }           

                }   
            }); 
        }

在回调结束时,我需要运行以下命令,但它现在在完成所有回调之前执行此函数。

        function displayResults() {
            if (totalSearch == 0)
            {
                alert("No results found");
                $('#loading').removeClass('loading');
                $('#main').fadeIn(1000);
            }
            else {
                dynamicFaq();
                $('<p></p>').html(totalSearch + ' Results found').prependTo('#results-list');
                $('#results-list').fadeIn(1000);
                $('#loading').removeClass('loading');
            }   
        }

【问题讨论】:

    标签: javascript jquery xml json


    【解决方案1】:

    如果我理解正确的话,你想加载 1 个 xml 文件,循环,然后开始加载下一个 xml 文件。如果是这样,这里有一个小伪代码:

    function doSearch(int xmlFileIterator){
        if (xmlFileIterator < allContent.length) {
            ...
            contentID = allContent[xmlFileIterator];
            ...
            getXml(xmlFileIterator);
        } else {
            //no more xml files left
            displayResults();
        }
    }
    
    function getXml(int xmlFileIterator) {
        ...
            success: function() {
                ...
                doSearch(++xmlFileIterator);
            }
    }
    

    第一个调用是doSearch(0),它加载了第一个xml 文件。加载文件并完成循环(成功)后,您可以使用更大的数字(迭代器)再次调用 doSearch 函数。

    【讨论】:

      【解决方案2】:

      我看到您的 AJAX 调用是异步的。尝试使用

                  ....
                  type: "GET",
                  url: langFile,
                  async: false,
                  dataType: "xml",
                  .....
      

      【讨论】:

      • 永远不要使用同步调用,永远不要。它会卡住浏览器(这只是您应该避免同步调用的一方面)。
      • 异步工作,但是它冻结了 IE7/8 相当长的一段时间,从长远来看这并不是一个真正的选择,我现在正在查看以下选项,然后重新评估我的答案。感谢 Indoknight
      【解决方案3】:

      维护一个 ajax 队列,这样 ajax 调用将被一一完成。再加上维护一个全局变量 searchedCount,它将维护主要 xml 的处理方式。

      在 ajax 的完整回调中检查 searchedCount 并调用 displayResults 函数。

      var allContent = ["xmlfile1", "xmlfile2", "xmlfile3", "xmlfile4"];
      var totalSearch = 0;
      var countSearch = 0;
      var searchedCount = 0;
      
      var ajaxQueue = $({});
      $.ajaxQueue = function (ajaxOpts) {
          // Hold the original complete function.
          var oldComplete = ajaxOpts.complete;
          // Queue our ajax request.
          ajaxQueue.queue(function (next) {
              // Create a complete callback to fire the next event in the queue.
              ajaxOpts.complete = function () {
                  // Fire the original complete if it was there.
                  if (oldComplete) {
                      oldComplete.apply(this, arguments);
                  }
                  // Run the next query in the queue.
                  next();
              };
              // Run the query.
              $.ajax(ajaxOpts);
          });
      };
      
      function doSearch() {
      
          var oldContentID = contentID;
          searchedCount = 0;
          for (iSearch = 0; iSearch < allContent.length; iSearch++) {
              totalSearch = totalSearch + countSearch;
              contentID = allContent[iSearch];
              defineContent();
              searchedCount++;
              getXML();
      
          }
      }
      
      function getXML() {
          $.ajaxQueue({
              type: "GET",
              url: langFile,
              dataType: "xml",
              beforeSend: function () {
      
                  $('#results-list').empty();
                  $('#results-list').hide();
                  $('#loading').addClass('loading');
              },
              success: function (xml) {
      
                  //your code 
      
              },
              complete: function () {
                  if (searchedCount == allContent.length) {
                      displayResults()
                  }
              }
          });
      }
      

      【讨论】:

        猜你喜欢
        • 2013-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-26
        • 1970-01-01
        • 2021-10-02
        • 2022-06-22
        相关资源
        最近更新 更多