jQuery.getJSON 取得跨網域(cross domain)的JSON資料

在jQuery1.2之後,jQuery.getJSON支援cross domain取得JSON資料

client端:

<script>
$.getJSON("http://your.url.com/jsoncallback=?",
        function(data){
          $.each(data.items, function(i,item){
            $("<img/>").attr("src", item.media.m).appendTo("#images");           
          });
        });
</script>

要注意的是雖然我們是傳"jsoncallback=?",jQuery會自動地把?轉換成適當地method name。 所以實際上傳給server端的內容是類似"jsoncallback=jsonp1236848595320"這樣的。

在server端:
要把JSON格式的資料用()包起來並且在最前方加上傳進來的jsoncallback的值,而不是直接傳回JSON格式的資料

<?php   
    $jsonp = $_GET["jsoncallback"];
    echo $jsonp."(".json_format_data.")";
?>

參考資料:

jQuery.getJSON documentation

Related Posts with Thumbnails

Comments (1)

Girvan四月 2nd, 2009 at 10:26 下午

你應該加個推推王的… …

Leave a comment

Your comment