【问题标题】:How to retrieve data from JSON file using Jquery and ajax?如何使用 Jquery 和 ajax 从 JSON 文件中检索数据?
【发布时间】:2016-03-14 19:05:36
【问题描述】:

我今天发生了一件奇怪的事情:我试图使用 jquery 和 ajax 从 JSON 文件中检索一些数据,并将这些数据显示在网页上。我在 Internet 上找到的这个示例在基本操作系统上为我工作。当我尝试从具有 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>

此外,当我单击“获取 JSON 数据”时,控制台中会显示以下内容:

【问题讨论】:

  • 你无法从本地文件中检索json,所以你应该设置一个服务器,比如:localhost:8080/C9HS_19.html

标签: jquery json ajax


【解决方案1】:

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

【讨论】:

  • 您无法从本地文件中检索 json
  • 好的,但是为什么在我的基础操作系统上它可以工作?它在网页上显示了 json 对象。
  • 对不起,我知道,你不能通过 ajax 本地文件调用,没有服务器
  • 创建简单的nodejs服务器,或者设置apach,并使用它
  • 好的,但我的问题仍然可用。为什么在我的基础操作系统上它可以在不使用任何网络服务器的情况下工作?
【解决方案2】:

您可以检查您的 JSON 源是否需要互联网连接,如果是,则您的虚拟机必须有互联网连接。

> 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);

【讨论】:

  • 但是我的虚拟机有互联网连接。
  • 尝试直接通过VM浏览器地址栏访问,查看是否返回数据!
  • 抱歉,我不明白你要我做什么。
  • 我的意思是你正在使用“data19.json”的 URL,在浏览器地址栏中提供完整的 URL 并回车,如果显示 JSON 数据,将该 URL 放入 AJAX url 参数中,似乎是 URL 问题,它找不到 URL,因此抛出 404 错误。
【解决方案3】:

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

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

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

  console.log(items);

工作样本here

【讨论】:

  • 非常感谢。我的问题不是代码,而是为什么它不能在我的 VM 上运行。它仅适用于我的基本操作系统。
【解决方案4】:

我认为这将解决问题。我自己试过了,你可以用。


<!-- 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 -->

【讨论】:

  • 这并不能真正回答问题。如果您有其他问题,可以点击 提问。一旦你有足够的reputation,你也可以add a bounty 来引起对这个问题的更多关注。 - From Review
  • 我是也门人,我不会说英语,这个答案是正确的。我试过了:-)
  • 我只是想帮忙。
【解决方案5】:

请尝试在这种情况下使用 Mozilla 浏览器。我在 chrome 中也遇到了同样的问题,但它在 mozilla 上运行良好。 尝试为 ajax 请求添加值为“Get”的“type”参数。 参考这个 -

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

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

【讨论】:

  • jQuery 的好处之一是跨浏览器支持,如果它适用于一个而不是另一个,则代码有问题
猜你喜欢
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
相关资源
最近更新 更多