通过jQuery显示XML搜索

时间:2019-03-07 12:10:31

标签: javascript jquery ajax xml

我必须基于XML文件构建一个动态网站。目的是拥有用户文本输入,并使用该输入来过滤XML并显示具有匹配项的每个对象。现在,我已经搜索了很长时间,没有找到任何可以满足我需要的东西,我自己也无法解决。我最好的就是这个脚本。我还没有更改所有内容以适合我的数据,但是我必须在控制台中显示record变量,这很棒。问题是:我无法显示它。我想显示标签和结果的值,但无法正常工作。 如果有人可以帮助我正确显示结果,或者建议一种更好的方法来筛选和显示XML,我希望听到您的想法。

谢谢。

PS:xml中的xml是链接

//back to top button
window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("topBtn").style.display = "block";
  } else {
    document.getElementById("topBtn").style.display = "none";
  }
}

function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
//reloading the website
window.onload = function() {
  reloadFunction()
};

function reloadFunction() {}

//Full source
$(document).ready(function() {

  //Global Variables
  var XMLSource = $('#data').attr('xmlData');
  var keyword = '';
  var pub = '';

  var i = 0;

  $("#searchButton").click(function() {
    keyword = $("input#term").val();

    //Reset any message
    var errMsg = '';
    pub = '';

    //Check if a keyword exists
    if (keyword == '') {
      errMsg += 'Please enter a search keyword';
    } else {
      searchThis();
    }

    if (errMsg != '') {
      pub += '<div class="error">';
      pub += errMsg;
      pub += '</div>';
    }

    //Show error
    $('#result').html(pub);

  });

  //Use enter key to trigger the search query  
  $("input#term").keypress(function(e) {
    var key = e.which;
    if (key == 13) {
      $("#searchButton").click();
      return false;
    }
  });

  function searchThis() {
    $.ajax({
      type: "GET",
      url: XMLSource,
      dataType: "xml",
      success: function(xml) {
        loadPublication(xml)
      }
    });
  }

  function loadPublication(xmlData) {
    i = 0;
    var row;
    var searchExp = "";
    var ppid = "P";

    $(xmlData).find('test').each(function() {
      // Check if a site URL attr exists		
      if ($(this).find('row')) {



        var record = $(this).find('row').text();
        var archive = $(this).find('Site');

        //Escape characters in keyword expression and use global match	
        RegExp.escape = function(keyword) {
          return keyword.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
        };

        //Keyword expression will be case agnostic
        var exp = new RegExp(keyword, "i");

        //Use formated keyword as the default search
        searchExp = record.match(exp);
        console.log(record);
        document.getElementById("output").innerHTML = record;

        //If the search expression is not null
        if (searchExp != null) {

          //Start building the result
          if ((i % 2) == 0) {
            row = 'even';
          } else {
            row = 'odd';
          }

          if ($(this).find('ID') != ppid) {
            ppid = $(this).find('ID');

            i++;

            //Grouped header row with URL links from the xml attr
            pub += '<tr id="wrapper" class="row ' + row + '">' +
              '<td colspan="8">' +
              '<a onclick="javascript:expgroupby(this);return false;" href="javascript:">' +
              '<img name="collapse" alt="expand" src="/_layouts/images/plus.gif" border="0" /></a>' +
              '<a href="http://project.com/sites/tp/Projects/' + $(this).find('url').attr('address') + '">' + '  ' + $(this).attr('PID') + ' - ' + $(this).attr('Description') + ' - ' + $(this).attr('Lead') + '</a></td>' +
              '</tr>';

          }

          //Bottom grouped expand detail fields
          pub += '<tr id="item" style="display: none;">' +
            '<td valign="top" class="col2">' + $(this).find('ID') + '</td>' +
            '<td valign="top" class="col3">' + $(this).find('Site') + '</td>' +
            '<td valign="top" class="col4">' + $(this).find('Gorge') + '</td>' +
            '<td valign="top" class="col5">' + $(this).find('WO') + '</td>' +
            '<td valign="top" class="col6">' + $(this).find('WO') + '</td>' +
            '<td valign="top" class="col7">' + $(this).find('WO') + '</td>' +
            '<td valign="top" class="col8">' + $(this).find('Archive').text() + '</td>' +
            '</tr>';
        }
      }
    });


    if (i == 0) {
      pub += '<div class="error">';
      pub += 'No results were found!';
      pub += '</div>';

      //Populate the result
      $('#result').html(pub);
    } else {
      //Pass the result set
      showResult(pub);
    }
  }

  function showResult(resultSet) {

    //Show the result with the titles of the column fields
    pub = '<div class="message">There are ' + i + ' results!</div>';
    pub += '<table id="grid" border="0">';
    pub += '<thead><tr><td><th class="mess">PPID - Project Description - Lead PM</th></td></tr>';
    pub += '<tr><th class="col2">WO Number</th>';
    pub += '<th class="col3">WO Description</th>';
    pub += '<th class="col4">Project Manager</th>';
    pub += '<th class="col5">Status</th>';
    pub += '<th class="col6">XRef</th>';
    pub += '<th class="col7">Program</th>';
    pub += '<th class="col8">Archive Status</th>';
    pub += '</tr></thead>';
    pub += '<tbody>';

    pub += resultSet;

    pub += '</tbody>';
    pub += '</table>';

    //Populate the results
    $('#result').html(pub)

    // $('#grid').tablesorter();
  }
});


//Grouping of the results
function expgroupby(e) {
  docElts = document.all;
  numElts = docElts.length;
  images = e.getElementsByTagName("IMG");
  img = images[0];
  srcPath = img.src;
  index = srcPath.lastIndexOf("/");
  imgName = srcPath.slice(index + 1);
  var b = "auto";
  if (imgName == "plus.gif") {
    b = "";
    img.src = "/_layouts/images/minus.gif"
  } else {
    b = "none";
    img.src = "/_layouts/images/plus.gif"
  }
  oldName = img.name;
  img.name = img.alt;
  spanNode = img;
  while (spanNode != null) {
    spanNode = spanNode.parentNode;
    if (spanNode != null && spanNode.id != null && spanNode.id == "wrapper") break
  }

  while (spanNode.nextSibling != null && spanNode.nextSibling.id != "wrapper") {
    spanNode = spanNode.nextSibling;
    spanNode.style.display = b;
  }
}
* {
  box-sizing: border-box;
}

#topBtn {
  display: none;
  height: 64px;
  width: 64px;
  position: fixed;
  bottom: 10px;
  right: 30px;
  border: none;
  outline: none;
  cursor: pointer;
  background-color: rgba(0, 0, 0, 0);
  background-image: url("../img/icons/back-to-top.png")
}


/* body*/

body {
  font-family: Arial;
  margin: 0;
}

.header {
  padding: 40px;
  text-align: center;
  background: black;
  color: white;
}

.navbar {
  display: flex;
  top: 0;
  position: sticky;
  background-color: #333;
}

.navbar a {
  color: white;
  padding: 14px 20px;
  text-decoration: none;
  text-align: center;
}

.navbar a:hover {
  background-color: #ddd;
  color: black;
}

.row {
  display: flex;
  flex-wrap: wrap;
}

.side {
  flex: 20%;
  background-color: #f1f1f1;
  padding: 20px;
}

.main {
  flex: 80%;
  background-color: white;
  padding: 20px;
}

.fakeimg {
  background-color: #aaa;
  width: 100%;
  padding: 20px;
}

.footer {
  padding: 20px;
  text-align: center;
  background: #ddd;
}

#logo_dai {
  width: 92px;
  height: 36px;
}

#logo_unikoeln {
  width: 178px;
  height: 36px;
}


/* Responsive layout - when the screen is less than 700px wide, make the two columns stack on top of each other instead of next to each other */

@media screen and (max-width: 700px) {
  .row,
  .navbar {
    flex-direction: column;
  }
}
<!DOCTYPE html>
<html lang="de">

<head>
  <meta charset="UTF-8">
  <title>Brandberg</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script id="data" type="text/javascript" src="js/script.js" xmlData="https://raw.githubusercontent.com/Demirro/Webportal2/master/ToS_spaces.xml"></script>
  <!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.js"></script> -->

  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <!-- Header -->
  <header id="header">
    <div class="header" id="header">
      <h1>My Website</h1>
      <p>With a <b>flexible</b> layout.</p>
    </div>
  </header>
  <!-- Navigation Bar -->
  <div class="navbar">
    <a href="#">Link</a>
    <a href="#">Link</a>
    <a href="#">Link</a>
    <a href="index.html#footer"> Impressum</a>
  </div>

  <!-- Content -->
  <div class="row">
    <div class="side">
      <form>
        <fieldset>
          <legend>
            <h2>Search:</h2>
          </legend>
          <!--<label for="search">Search: </label>-->
          <input type="text" id="term" name="ter" autocomplete="off" placeholder="search something...">
          <label for="submit"></label>
          <input type="button" id="searchButton" name="submit" value="submit">
          <!-- <h3>Categories:</h3>
                    <label for="category">Choose a category:</label>
                    <select id="category">
                      <option selected>All</option>
                      <option>Images</option>
                      <option>Books</option>
                      <option>Site</option>
                    </select> -->
          <!-- <input type="checkbox" name="c1" value="Images"> Images<br>
                    <input type="checkbox" name="c2" value="Books"> Books <br>
                    <input type="checkbox" name="c3" value="Sites"> Sites <br><br> -->
        </fieldset>
      </form>
    </div>
    <div class="main">
      <main>
        <p id="output"></p>
        <div id="result">
          <table class="tablesorter"></table>
        </div>
      </main>
    </div>
  </div>

  <!-- Footer -->
  <div class="footer" id="footer">
    <button onclick="topFunction()" id="topBtn" title="Nach oben"></button>
    <a href="https://www.dainst.org/dai/meldungen">
      <img SRC="img/logo_dai.png" alt="logo_dai" id="logo_dai"></a>
    <a href="http://archaeologie.uni-koeln.de">
      <img SRC="img/logo_unikoeln.png" alt="logo_unikoeln" id="logo_unikoeln"></a>
  </div>

  <!-- <script src="js/script.js"></script> -->
</body>

</html>

我的JSFiddle:https://jsfiddle.net/Demirro/fx7b4rnd/3/

0 个答案:

没有答案