将 getJSON 更改为 JSONP

IT技术 javascript jquery json jsonp
2021-03-08 03:54:36

我有这个代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $.getJSON('http://example.com/api/get_cats', function(fbResults) {
            document.write(fbResults.cats[0].title);
        });
    });
</script>

如何更改此代码:

<script>
    $(document).ready(function() {
        $.getJSON('http://example.com/api/get_cats', function(fbResults) {
            document.write(fbResults.cats[0].title);
        });
    });
</script>

让它作为 JSONP 工作......这完全不同吗?

1个回答

实际上,您只需要添加?callback=?,其余的由 jQuery 完成。

$(document).ready(function() {
    $.getJSON('http://example.com/api/get_cats?callback=?', function(fbResults) {
        document.write(fbResults.cats[0].title);
    });
});
我收到“Uncaught SyntaxError: Unexpected token :”因为我的 php 正在返回 json。php端没有名字时如何格式化调用回调函数?
2021-05-08 03:54:36
@curtis 我添加output=jsonp&callback=?为参数是为了摆脱这个错误
2021-05-14 03:54:36