【问题标题】:Making and handling JSONP request using JavaScript使用 JavaScript 制作和处理 JSONP 请求
【发布时间】:2011-08-19 22:47:51
【问题描述】:

我想在客户端进行跨域请求,所以我选择了JSONP。我是 JSONP 的新手,想使用 JavaScript 而不是 jQuery 向 http://somedomain.com 发出请求。如果我获得示例 sn-p 以在 JavaScript 中使用 JSONP 发出和处理请求,这对我的开发将非常有帮助。

【问题讨论】:

标签: javascript jsonp


【解决方案1】:

这是一个从谷歌电子表格中获取数据的小例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
    <title>jsonp</title>
</head>
<body>
    <span></span>
    <script>
        //this function is the callback, it needs to be a global variable
        function readResponse(response){
            document.getElementsByTagName('SPAN')[0].innerHTML = response.feed.entry.length + ' entries returned';
            console.log(response);
        }
        (function(){
            //note the "readResponse" at the end
            var src = 'http://spreadsheets.google.com/feeds/list/o13394135408524254648.240766968415752635/od6/public/values?alt=json-in-script&callback=readResponse',
                script = document.createElement('SCRIPT');
            script.src = src;
            document.body.appendChild(script);
        })();

    </script>
</body>
</html>

与此示例相关的一条评论。如果您想使用自己的 Google 电子表格,您需要将其公开分享并发布。

【讨论】:

  • 很好的例子!这是另一个.. 它是一个 JSBin,可用于来自 Wikipedia 的 fiddle with JSONP。它在this answer中被引用。
猜你喜欢
  • 2013-10-02
  • 1970-01-01
  • 2013-07-20
  • 2013-11-18
  • 2011-10-05
  • 1970-01-01
相关资源
最近更新 更多