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

时间:2015-12-09 13:26:38

标签: jquery json ajax

今天发生了一件奇怪的事:我试图使用jquery和ajax从JSON文件中检索一些数据,并在网页上显示这些数据。我在互联网上找到的这个例子在基础操作系统上为我工作。当我尝试从具有Win10操作系统的虚拟机运行它时,它不起作用,这意味着它会引发我:alert('There was a problem with the server. Try again soon!');。为什么? 非常感谢提前!

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

 {
  "one": "Learned Optimism",
  "two": "Deliberate Practice",
  "three": "Getting Things Done"
}

我的脚本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!');
         }
       }
    });
  });
});

我的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>

当我点击&#34;获取JSON数据&#34;这是控制台中出现的内容: enter image description here

5 个答案:

答案 0 :(得分:5)

你的代码是corect,你必须将代码移动到服务器,在服务器上你的ajax调用json,一切都会正常工作。

答案 1 :(得分:0)

您可以检查您的JSON源是否需要互联网连接,如果是,则您的VM必须能够正常连接互联网。

> Edit: Work around to read local JSON external file.
> 1. Create data.json file
> 2. Copy data into this file, for example:
>     data = '[{"Id" : "1", "name" : "abc"},{"id" : "2", "name" : "xyz"}]';
> 3. Include path for this file as reference:    <script type="text/javascript" src="data.json"></script>
> 4. Read JSON data by:    var jsonData = JSON.parse(data);

答案 2 :(得分:0)

您提供的json数据(内部数据变量)不是数组,而是具有属性名称和值的单个对象。所以不要遍历它们。而是遍历这些属性,并使用属性访问该值。

 items=[]; 
  for(r in data)
  {
      var key =r;
      var val=data[r];

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

  console.log(items);

工作样本here

答案 3 :(得分:0)

请尝试在此方案中使用mozilla浏览器。我也在chrome中面临同样的问题,但它在mozilla上工作正常。 尝试添加&#34;输入&#34;参数值为#34;得到&#34;对于ajax请求。 参考这个 -

$.ajax({
    type: "Get",
    url: "data.json",
    dataType: "json",
    success: function(data) {

    },
    error: function(){
        alert("json not found");
    }
});

答案 4 :(得分:-1)

我认为这样可以解决问题。我自己尝试过。我可以使用它。

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>How to retrieve data from JSON file using Jquery and ajax?</title>
    </head>
    <body>
    <div id="info"></div>
    </body>


----------


    <script type="text/javascript">
                    // script for Load 6 items at a time
                    var j=0; // index for start load in the object
                    var xdata; //A global variable for accessing it from inside the functions. it will load the file and do not want to read the file every time 
                    //loading the JSON file to object by Ajax
                    var xreq = new XMLHttpRequest();
                    xreq.open('GET', 'file.json');
                    xreq.onload = function () {
                        //convert the file from text to object after opened it , on load the file
                        xdata = JSON.parse(xreq.responseText);
                        // call funcation to Build the page
                        addHtml(xdata, j);
                        // added 6 to the index for start loading from the next items
                        j = j + 6;
                    };
                    //send ajax
                    xreq.send();

                    // when the page is ready and already the scroll access to end page call the building function again
                    $(document).ready(function () {
                            $(window).scroll(function () {
                                // get the scroll Position
                                var scrollPosition = $(window).scrollTop();
                                // Multiplication operation in 1.2 in order to call the function before arrival the end of the page with 20%
                                if (scrollPosition >= $(document).height() - ($(window).height())*1.2 && j < xdata.length) {
                                    addHtml(xdata, j);
                                    j = j + 6;
                                    xreq.send();
                                }
                            });
                        });

                    //funcation to Build the page
                    function addHtml(data,i) {
                        var info = document.getElementById("info");
                        var HtmlText ="";
                        // insert the HTML items before end a page
                        info.insertAdjacentHTML('beforeend',HtmlText);
                    }
                    </script>


----------


    </html>

<!-- end snippet Alwahashi 2017 -->