使用JavaScript制作和处理JSONP请求

Bal*_*aji 7 javascript jsonp

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

Mic*_*Mic 11

以下是从Google电子表格中获取数据的小示例:

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

一个评论与此示例有关.如果您想使用自己的Google电子表格,则需要将其作为公开分享,然后发布.