jQuery+JSONP返回空数据

jQuery + JSONP return empty data?

本文关键字:数据 返回 jQuery+JSONP      更新时间:2023-09-26

好的,由于某种原因,我的脚本没有从从第三方站点获取的JSON文件中返回任何数据。

这是代码

$(document).ready(function() {
    var url =  "http://konachan.net/post/index.json?limit=20&tags=hatsune_miku";
    $.getJSON(url + "&callback=?", null, function(items) {
        for(i in items) {
            item = items[i];
                        $("#content").append('<div class="product" id="product-' + item.id + '"><img src="' + item.preview_url + '" width="135" height="138"/><div class="title">' + item.author + '</div><div class="description" style="overflow:hidden;">' + item.tags + '</div><div class="clear"></div></div>');
        }
    });
});

它到底怎么了?

编辑:PHP Curl仍然没有工作:http://pastebin.com/5gVUviZw

我点击了urlhttp://konachan.net/post/index.json?limit=20&tags=hatsune_miku&callback=使用回调参数进行测试,并且我没有看到JSON封装在函数名中。

JSONP的工作方式是,当您传递回调函数名时,服务器应该将JSON封装在该函数中,这样当从服务器返回JavaScript时,就会调用回调函数,并将JSON数据作为参数传入。

// "test" was the callback parameter I used
test({ "my": "data" , "returned_from" : "server" });

在后台,JSONP使用脚本元素从远程服务器下载JavaScript(JSON)

由于url中的JSON没有封装在函数名中,因此您无法轻松跨域访问它。以下是维基百科上关于带填充的JSON的文章,它对此进行了更详细的解释。

也许您可以查看该特定资源的文档,因为它们很可能使用了除"callback"之外的参数来指定一个回调函数来"填充"数据。

如果没有参数将结果封装在函数名称中,则可以使用服务器端代理获取JSON响应,并将其封装在函数中,然后将其返回到客户端。

因为从第三方站点返回的代码显然不是为JsonP调用而生成的,它只是返回一个包含[]等数据的数组。但是它应该返回这个数组并调用一个js函数,这样您的脚本就可以访问像myCallbackFunc([])这样的数据。

在此页面上搜索jsonp以获取更多信息http://api.jquery.com/jQuery.ajax/.