Making and handling JSONP request using JavaScript

这一生的挚爱 提交于 2019-12-17 13:57:15

问题


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.


回答1:


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>

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.



来源:https://stackoverflow.com/questions/5907777/making-and-handling-jsonp-request-using-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!