【问题标题】:Undefined on getting data from JSON从 JSON 获取数据时未定义
【发布时间】:2016-06-23 23:52:04
【问题描述】:

我从 JSON 文件中获取数据,但得到了这个输出(我从检查元素复制 - 编辑为 HTML)

<li>
    <a href="function" link()="" {="" [native="" code]="" }="" class="ui-btn ui-btn-icon-right ui-icon-carat-r">undefined</a>
</li>

我使用的脚本是

(function($) {
    var url = 'http://divakarparashar.hol.es/innovation/mobile/protected/json/news.json';

    $.ajax({
        type: 'GET',
        url: url,
        async: true,
        jsonpCallback: 'MyJSONPCallback',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(json){
            $.each(json, function(i, j) {
                $("#links").append("<li><a href=" + j.link + " class='ui-btn ui-btn-icon-right ui-icon-carat-r'>" + j.text + "</li>");
                console.log(j.link + j.text);
                //used console.log to just run a check, same output there too
            });
        },
        error: function(e) {
            console.log(e.message);
        }
    });
})(jQuery);

console.log 中的输出

function link() { [本机代码] }未定义

当我在 localhost 上运行此文件时,我也尝试使用来自本地服务器的文件,但它给出了相同的输出。

【问题讨论】:

  • 另外,如果您在每个之前添加console.log(json);,您将看到 json 只是第一个对象。 link 方法属于字符串原型(将字符串转换为锚点),这就是为什么您首先看到的是原生函数。
  • 这个错误是因为你的JSONP格式不正确,对象需要用[]包围,例如:MyJSONPCallback([{ "link":"#", "text":"This is news 1" }, ... ]);
  • @RoryMcCrossan 谢谢。在 MyJSONPCallback([{ "link":"#", "text":"This is news 1" }, ... ]) 之后一切都按预期工作,希望在 }])
  • 没问题,很高兴为您提供帮助。我将其添加为您的答案。

标签: javascript jquery json


【解决方案1】:

我点击了您正在访问的 URL,并注意到它不是以 json 格式提供的...在 PHP 中,我的 JSON 数据使用以下方式提供:

header('content-type: application/json; charset=utf-8');

您需要在服务器端执行类似的操作,否则您需要通过 ajax 调用请求 txt 或 javascript 而不是 json。

【讨论】:

    【解决方案2】:

    错误是因为你的JSONP格式不正确,对象需要用[]包围,例如:

    MyJSONPCallback([
        { 
            "link":"#", 
            "text":"This is news 1" 
        }, 
        // other objects... 
    ])
    

    【讨论】:

      【解决方案3】:

      你对your url返回的JSON还好吗??

      因为我有这个:

      MyJSONPCallback({ "link":"#", "text":"This is news 1" }, { "link":"#", "text":"This is news 2" }, { "link":"#", "text":"This is news 3" })
      

      而且它不是一个有效的 JSON,也不是一个数组。这必须返回类似:

      [{ "link":"#", "text":"This is news 1" }, { "link":"#", "text":"This is news 2" }, { "link":"#", "text":"This is news 3" }] 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-06
        • 1970-01-01
        • 1970-01-01
        • 2017-04-02
        • 2018-07-08
        • 2021-09-24
        • 2018-09-15
        相关资源
        最近更新 更多