将getJSON更改为JSONP

Sat*_*000 7 javascript jquery json jsonp

我有这个代码:

<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>
Run Code Online (Sandbox Code Playgroud)

如何更改此代码:

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

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

Jil*_*Vie 34

实际上,你只需要添加?callback=?,jQuery完成剩下的工作.

$(document).ready(function() {
    $.getJSON('http://example.com/api/get_cats?callback=?', function(fbResults) {
        document.write(fbResults.cats[0].title);
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 我得到"Uncaught SyntaxError:Unexpected token:"因为我的php正在返回json.如果没有名字,如何格式化php端调用回调函数? (8认同)
  • @curtis我添加了output = jsonp&callback =?作为参数,以摆脱此错误 (2认同)