Query JSON data from Azure Blob Storage with jQuery

主宰稳场 提交于 2019-11-30 10:23:18

Well, apparently Azure blob storage doesn't support JSONP straightaway, but it can be done.

For example, if I store this JSON in an Azure blob:

{"Name":"Valeriano","Surname":"Tortola"}

And I try:

<script type="text/javascript">

    $.getJSON("https://myaccount.blob.core.windows.net/jsonptests/data?jsoncallback=?",
             function (data) {
                 alert(data.Name);
             });
</script>

It doesn't work. Well, actually the browser download the data but there is no call back. So, considering how JSONP works, if I save this JSON with the callback function:

dataCallback({"Name":"Valeriano","Surname":"Tortola"})

And I do:

<script type="text/javascript">

    function dataCallback(data) {
        alert(data.Name);
    }
</script>

<script type="text/javascript" src="https://myaccount.blob.core.windows.net/jsonptests/data"></script>

Then the dataCallBack get executed :) The disadvantage is that the callback function name has to be harcoded, but it's better than nothing.

Happy days, but if anyone has a better way would be great.

Cheers.

The Windows Azure Blob Storage REST interface returns XML (POX), not JSON... However it's simple to query from JavaScript! Call you container URL with restype=container and comp=list:

$(document).ready(function () {         
    // Retrieve list of Blobs
    var containerUrl = 'http://tcontepub.blob.core.windows.net/json/';
    $.ajax({
        type: 'GET',
        url: containerUrl + '?restype=container&comp=list',
        dataType: 'xml',
        success: listBlobs
    });
});

Then you can do a basic parsing of the XML returned. Here I will extract the URL and display it in a div.

function listBlobs(xml) {
    $(xml).find('Blob').each(function() {
        var url = $(this).find('Url').text();
        $('#panel').append(url + '<br />');
    });
}

I have tested this in an HTML page that was itself stored as a Blob.

Unfortunately, I'm afraid the JavaScript "Same Origin Policy" will make this fairly difficult to use in practice.

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