Monday, August 24, 2015

Quick & Dirty JSON Web Service call with jQuery

Use this little snippet to make a nice little async call using jquery and "promises"!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

var url = SOME_URL_THAT_RETURNS_JSON;

var promise = $.getJSON(url); 

promise.then(successFunc);

function successFunc(data)
{
alert("$.getJSON returns  " + data.SOMEDATA);
}

UPDATE: Discovered that there is a difference between SharePoint online and on-premise concerning ajax.

online supports minimal json (which is what you get with getJSON and on-premise does not!

for on-premise you must explicity set json-verbose, something like so:

$.ajax({ url: Url, method: 'GET', beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json; odata=verbose"); },
cache: true, error: function (data) { ////failure },
success: function (data) { ////success } });

No comments:

Post a Comment