【发布时间】: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