IT story

JSONP와 함께 .ajax ()를 사용하는 기본 예?

hot-time 2020. 5. 18. 08:09
반응형

JSONP와 함께 .ajax ()를 사용하는 기본 예?


JSONP를 시작하는 방법을 알려주는 사람이 있습니까?

암호:

$('document').ready(function() {
    var pm_url = 'http://twitter.com/status';
    pm_url += '/user_timeline/stephenfry.json';
    pm_url += '?count=10&callback=photos';
    var photos = function (data) {
     alert(data);
    };
    $.ajax({
        url: pm_url,
        dataType: 'jsonp',
        jsonpCallback: 'photos',
        jsonp: false,
    });
});

피들 : http://jsfiddle.net/R7EPt/6/

문서에서 해결할 수있는 한 경고를 표시해야합니다 : 아닙니다 (그러나 오류도 발생하지 않습니다).

감사.


JSONPXMLHttpRequest 와 동일한 도메인 정책 을 극복하기위한 간단한 방법입니다 . (알다시피 AJAX (XMLHttpRequest) 요청을 다른 도메인으로 보낼 수는 없습니다 .)

따라서 XMLHttpRequest 를 사용하는 대신 JS가 다른 도메인에서 데이터를 가져 오려면 일반적으로 JS 파일을로드하는 데 사용하는 스크립트 HTMLl 태그 를 사용해야 합니다. 이상한데?

것입니다 - 밝혀 스크립트 태그와 유사한 방식으로 사용할 수있는 XMLHttpRequest를 ! 이것 좀 봐:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";

당신은 끝낼 것이다 스크립트 그 후 같은 외모가 데이터를로드하도록 세그먼트 :

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

그러나 이것은 스크립트 태그 에서이 배열을 가져와야하기 때문에 약간 불편 합니다. 따라서 JSONP 제작자는 이것이 더 잘 작동한다고 결정했습니다.

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";

공지 사항 my_callback의 저기 기능? 따라서 JSONP 서버가 요청을 받고 콜백 매개 변수를 찾으면 일반 JS 배열을 반환하는 대신 다음을 반환합니다.

my_callback({['some string 1', 'some data', 'whatever data']});

이익이 어디 있는지 확인하십시오. 이제 데이터를 가져 오면 자동 콜백 ( my_callback )이 실행됩니다. JSONP 에 대해 알아야 할 것은 콜백 및 스크립트 태그입니다.


참고 :
이들은 JSONP 사용법의 간단한 예이며 프로덕션 준비 스크립트가 아닙니다.

RAW JavaScript 데모 (JSONP를 사용한 간단한 Twitter 피드) :

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


기본 jQuery 예 (JSONP를 사용한 간단한 Twitter 피드) :

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONPJSON with Padding을 나타냅니다 . (대부분의 사람들이“패딩”이라고 생각하는 것과는 아무 관련이 없기 때문에 이름이 매우 낮은 기술입니다.)


jQuery를 사용하여 JSONP로 작업하는 더 쉬운 방법이 있습니다

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.


In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.

Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.

This does not work any more - as an exercise, see if you can replace it with the Github API:

$('document').ready(function() {
    var pm_url = 'http://twitter.com/status';
    pm_url += '/user_timeline/stephenfry.json';
    pm_url += '?count=10&callback=photos';
    $.ajax({
        url: pm_url,
        dataType: 'jsonp',
        jsonpCallback: 'photos',
        jsonp: 'callback',
    });
});
function photos (data) {
    alert(data);
    console.log(data);
};

although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing

alert(JSON.stringify(data));

You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JQuery (cross-domain) JSONP Twitter example</title>
        <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.getJSON('https://api.github.com/gists?callback=?', function(response){
                    $.each(response.data, function(i, gist){
                        $('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" + 
                            (gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
                    });
                });
            });
        </script>
    </head>
    <body>
        <ul id="gists"></ul>
    </body>
</html>

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

참고URL : https://stackoverflow.com/questions/5943630/basic-example-of-using-ajax-with-jsonp

반응형