【问题标题】:getJson to load external data and display it as stringgetJson 加载外部数据并将其显示为字符串
【发布时间】:2014-02-20 15:03:21
【问题描述】:

给定一个位于http://codio.io/hugolpz/Cat-is-smart/data/dict.json 的 JSON 文件。

鉴于我想加载它,然后显示它(把手放在它上面并使用它)。

我因此使用:

$.getJSON( "http://codio.io/hugolpz/Cat-is-smart/data/dict.json", function( json ) {
  console.log("This step is fired."); // OR NOT !
  alert( "JSON Data: " + JSON.stringify(json) );
 });

$.ajax({
        url: "http://codio.io/hugolpz/Cat-is-smart/data/dict.json",
        dataType: 'json',
        success: function(json2) {
            alert( "JSON Data: " + JSON.stringify(json2) );
        }
});

即使在同一个域上测试也不起作用。

我做错了什么?如何解决。

http://jsfiddle.net/676V5/1/

【问题讨论】:

  • 您的 JSON 文件不正确。请从您的 json 文件中删除注释行。(注释行不被 json link 识别)

标签: jquery json getjson


【解决方案1】:

无效的 JSON。建议以后用JSONLint这样的工具,省去很多麻烦!

【讨论】:

  • 就是这样,给ajax调用添加错误函数会在txtStatus中显示“parserError”
  • 该死的!!!!评论正在打破它!非常感谢。初学者,我在这个上花了 4 个小时
【解决方案2】:

如果你像下面这样使用 $(document).load,你可以得到 json 数据:

$(document).load( "http://codio.io/hugolpz/Cat-is-smart/data/dict.json", function( json ) 
{
     alert("finish"); // OR NOT !
     alert( "JSON Data: " + JSON.stringify(json) );
});

【讨论】:

    【解决方案3】:

    您调用的 url 可能不会返回 json 数据。它可能是字符串格式。 尝试将“dataType”更改为“text”而不是“json”

    【讨论】:

      【解决方案4】:

      总是检查错误...起初它给了我一个 parseError 失败;现在可以了:

      头:

      <script type='text/javascript'>
      $(document).ready(function(){
          var request = $.ajax({
            url: "http://codio.io/hugolpz/Cat-is-smart/data/dict.json",
            type: "GET",
            dataType: "html"
          });
      
          request.done(function( msg ) {
            $( "#log" ).html( msg );
          });
      
          request.fail(function( jqXHR, textStatus ) {
            alert( "Request failed: " + textStatus );
          });
      });
      </script>
      

      主体:

      <div id="log"></div>
      

      【讨论】:

        猜你喜欢
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多