使用JavaScript制作和处理JSONP请求 [英] Making and handling JSONP request using JavaScript

查看:154
本文介绍了使用JavaScript制作和处理JSONP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to make cross domain request in the client end, so I chose JSONP. I am new to JSONP and would like to make a request to http://somedomain.com using JavaScript and not jQuery. It would be very helpful for my development if I get sample snippet to make and handle a request using JSONP in JavaScript.

推荐答案

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

Here's a small example fetching data from a google spreadsheet:

<!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电子表格,则需要将其作为公开分享,然后发布。

One comment related to this example. If you want to play with your own google spreadsheet, you need to both share it as public, and publish it.

这篇关于使用JavaScript制作和处理JSONP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆