简体   繁体   English

如何通过 html 页面上的 ajax 调用加载外部 JSON 数据?

[英]How to load external JSON data via an ajax call on html page?

I created a dummy JSON file below to test out whether this html page works.我在下面创建了一个虚拟的 JSON 文件来测试这个 html 页面是否有效。 How do I load the data via ajax request?如何通过ajax请求加载数据? The only error I got is我得到的唯一错误是

Uncaught ReferenceError: data is not defined.未捕获的 ReferenceError:数据未定义。

How do I call this JSON file in my html page?我如何在我的 html 页面中调用这个 JSON 文件? Been trying but to no avail.一直在努力,但无济于事。 Got this from view-source if it helps如果有帮助,请从视图源中获取此信息

index.html索引.html

<!DOCTYPE HTML>
<html>
<head>
  <title>Matter Timeline</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="bootstrap.js"></script>
   <!-- load handlebars for templating, and create a template -->
  <script src="dist/handlebars-v4.0.11.js"></script>
  <script id="item-template" type="text/x-handlebars-template">
      {{target}} 
      <font color="#229954"><b>{{status_green}}</b></font>
      <font color="#A93226"><b>{{status_red}}</b></font>
      <br/>
      <font size="2" color="#2874A6">{{action}}</font> 
      <font size="2" color="#2874A6"><i>{{user}}</i></font> <br/> 
      <span class="tooltip-date">{{datetime}}</span>
  </script>

  <script src="dist/vis.js"></script>
  <link href="dist/vis-timeline-graph2d.min.css" rel="stylesheet" type="text/css" />
  <script>

    function resettimeline() {
        document.location.reload();
    };
  </script>     
</head>

<body>
<p>
  <center><h2>Matter Timeline</h2></center>
</p>
<div id="visualization"></div>

<script type="text/javascript">
  var groups = new vis.DataSet([
    {id: 0, content: 'Process/Task', value: 1},
    {id: 1, content: 'Req/Matter/Doc', value: 2}
  ]);

  var source = document.getElementById('item-template').innerHTML;
  var template = Handlebars.compile(document.getElementById('item-template').innerHTML);

  $.ajax({
    url: 'http://127.0.0.1:8887/data.json',
    dataType: "json",
    success: function(data) {
        //handle you data here
    }
  });

  // create visualization
  var container = document.getElementById('visualization');
  var options = {
    // option groupOrder can be a property name or a sort function
    // the sort function must compare two groups and return a value
    //     > 0 when a > b
    //     < 0 when a < b
    //       0 when a == b
    groupOrder: function (a, b) {
      return a.value - b.value;
    },
    orientation: {
        axis: 'top',
        item: 'top'
    },
    height: "85vh",
    template: template
    //timeAxis: {scale: 'day', step:3}
  };


  var timeline = new vis.Timeline(container);
  timeline.setOptions(options);
  timeline.setGroups(groups);
  timeline.setItems(data); 


  timeline.on('doubleClick', function (properties) {
    window.open('the_doc_url', 
                'newwindow', 
                'width=1000,height=600'); 
    return false;
  });

</script>
<br/>
<a href="javascript:resettimeline()">Fit to Width</a>
</body>
</html>

data.json数据.json

{
  "data": [
    { 
        id: 1, group: 0, 
        target: 'Request',
        action: 'from',
        user: 'SAS',
        datetime: '7/10',
        title: '<span class="tooltip-date">Date: 7/10/2017 09:00</span><br/>Req ID: R123',
        start: new Date(2017,9,7, 9,0,0,0)
    },
    { 
        id: 2, group: 0, 
        target: 'Request',
        action: 'by',
        user: 'Alice',
        datetime: '8/10',
        title: '<span class="tooltip-date">Date: 8/10/2017 13:34</span><br/>Req ID: R123',
        start: new Date(2017,9,8, 12,30,0,0)
    }
  ]
}

A JAX means "Asynchronous JavaScript And XML", and it seems that you missed the asynch part.一个JAX意思是“异步JavaScript和XML”,它似乎是你错过了非同步的一部分。 The code that is using the "data" variable is outside the callback, then this variable doesn't exist (or its value is undefined).使用“data”变量的代码在回调之外,则该变量不存在(或其值未定义)。

You need to use the json data after receiving it, something like this (it could probably be cleanup a little bit):您需要在接收到 json 数据后使用它,就像这样(可能会稍微清理一下):

$.ajax({
    url: 'http://127.0.0.1:8887/data.json',
    dataType: "json",
    success: function(data) {
        //handle you data here


            // create visualization
            var container = document.getElementById('visualization');
            var options = {
            // option groupOrder can be a property name or a sort function
            // the sort function must compare two groups and return a value
            //     > 0 when a > b
            //     < 0 when a < b
            //       0 when a == b
            groupOrder: function (a, b) {
              return a.value - b.value;
            },
            orientation: {
                axis: 'top',
                item: 'top'
            },
            height: "85vh",
            template: template
            //timeAxis: {scale: 'day', step:3}
            };


            var timeline = new vis.Timeline(container);
            timeline.setOptions(options);
            timeline.setGroups(groups);
            timeline.setItems(data.data); 


            timeline.on('doubleClick', function (properties) {
                window.open('the_doc_url', 
                            'newwindow', 
                            'width=1000,height=600'); 
                return false;
            });
      }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM