如何使用Jquery和Ajax从JSON文件检索数据?

Ion*_*nut 5 ajax jquery json

今天我发生了一件奇怪的事情:我试图使用jquery和ajax从JSON文件中检索一些数据,并将这些数据显示在网页上。我在Internet上找到的该示例在基本OS上为我工作。当我尝试从装有Win10 OS的虚拟机上运行它时,它不起作用,这意味着它使我无法进行以下操作:alert('There was a problem with the server. Try again soon!');。为什么?提前谢谢了!

这是在我的data19.json文件中:

 {
  "one": "Learned Optimism",
  "two": "Deliberate Practice",
  "three": "Getting Things Done"
}
Run Code Online (Sandbox Code Playgroud)

我的脚本script19.js是:

$(function() {  
  $('#clickme').click(function() {
       $.ajax({
       url: 'data19.json',
       dataType: 'json',
       success: function(data) {
          var items = [];

          $.each(data, function(key, val) {

            items.push('<li id="' + key + '">' + val + '</li>');    

          });

          $('<ul/>', {
             'class': 'interest-list',
             html: items.join('')
          }).appendTo('body');

       },
      statusCode: {
         404: function() {
           alert('There was a problem with the server.  Try again soon!');
         }
       }
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

我的HTML文件是:

 <!DOCTYPE html>
<html>
<head>
  <title>19. Using jQuery to retrieve JSON via AJAX</title>
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" src="script19.js"></script>
</head>
<body>
  <h1 id="title">19. Using jQuery to retrieve JSON via AJAX</h1>

  <a href="#" id="clickme">Get JSON Data</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

另外,当我单击“获取JSON数据”时,这就是控制台中显示的内容: 在此处输入图片说明

小智 6

您的代码是corect,必须将代码移到服务器上,在服务器上,您的ajax调用json,所有代码都将起作用。