将JSON结果从AJAX传递到HTML

时间:2019-01-29 09:19:38

标签: javascript html json ajax

我正在使用AJAX查询目录服务器,而我得到的结果是一个JSON对象。

我想使用分页浏览结果,每页记录数限制。我试图将JSON对象发送到html文件中的div,但是它不起作用。有解决方法吗?这是我的代码:

function myCallBack2(data) {
  var all_results = '';
  for (var i = 0; i < data.results.bindings.length; i++) {
    var bc = '';
    if (i % 2 == 0) {
      bc = '#b8cddb';
    } else {
      bc = '#f2f5f7';
    }
    all_results += '<div class="all_results" style="background-color:' + bc + '">';
    for (var j = 0; j < data.head.vars.length; j++) {
      var text = data.results.bindings[i][data.head.vars[j]].value;
      var type = data.results.bindings[i][data.head.vars[j]].type;
      all_results += '<div class="result_row">';
      if (type == ('literal')) {
        all_results += '<p> ' + data.head.vars[j] + ": " + text + '</p>';
      } else {
        all_results += '<a href=' + text + " title=" + data.head.vars[j] + '>' + text + '</a>';
      }
      all_results += '</div>';
    }
    all_results += '</div>';
  }
  $('#result').html(all_results);

}

function doSparql() {
  var myEndPoint = "http://localhost:3030/Test/query";
  name = document.getElementById("search").value;
  var requiredName = "?Author foaf:firstName \"" + name + "\".}";

  myQuery = ["PREFIX dcterms: <http://purl.org/dc/terms/>",
    "PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
    "PREFIX locah: <http://data.archiveshub.ac.uk/def/>",
    "SELECT ?Register ?Id ?Date ?Type",
    "WHERE{",
    "?Register dcterms:creator ?Author.",
    "?Register dcterms:identifier ?Id.",
    "?Register dcterms:type ?Type.",
    "?Register locah:dateCreatedAccumulatedString ?Date.",
    requiredName
  ].join(" ");
  console.log('myQuery: ' + myQuery);
  window.alert(myQuery);

  $.ajax({
    dataType: "jsonp",
    url: myEndPoint,
    data: {
      "query": myQuery,
      "output": "json"
    },
    success: myCallBack2,
    error: myError
  });
  console.log('After .ajax');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//raw.github.com/botmonster/jquery-bootpag/master/lib/jquery.bootpag.min.js"></script>

<div id="page-selection1" "></div>
<div id="result " class="result "></div>
<div id="page-selection2 "></div>

<script>
  $('#page-selection1,#page-selection2').bootpag({
    total: 50,
    page: 1,
    maxVisible: 5,
    leaps: true,
    firstLastUse: true,
    first: 'First',
    last: 'Last',
    wrapClass: 'pagination',
    activeClass: 'active',
    disabledClass: 'disabled',
    nextClass: 'next',
    prevClass: 'prev',
    lastClass: 'last',
    firstClass: 'first'
  }).on("page ", function(event, num) {
    $("#result ").html("Page " + num);

  });
</script>

我希望根据每页的限制在#result中显示部分结果,而不是第1页,第2页...。

0 个答案:

没有答案