问题
I am trying to pull in information from Asana API via JQuery.ajax() method. But no desired result is returned, or error showed.
Here is my partial code in JavaScript:
$(document).ready(function () {
$('#buttonCallAjax').click(function () {
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: "https://app.asana.com/api/1.0/users/me",
data: "{}",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "jsonp",
success: function (data) {
alert(data);
},
error: function (msg, url, line) {
alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
});
});
I have read a lot about ajax() method, but still figured out some options parameters in this method, like data, dataType(because this is cross-domain request, I used jsonp).
Can someone please help with successfully pulling in information from Asana API?
回答1:
Even though it looks as though the Asana API currently doesnt support JSONP, if in the future they do and you need to do authentication you can do it with the below code.
$.ajax( {
url : 'https://app.asana.com/api/1.0/users/me',
dataType : 'jsonp',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(API_KEY + ":"));
}
);
The btoa
function encodes to base64 but its not supported on all browsers so you may need to use some other library, if you need to support older browsers.
Update
The username name can also be set directly with jQuery no encoding or setting headers.
$.ajax( {
url : 'https://app.asana.com/api/1.0/users/me',
dataType : 'jsonp',
username : API_KEY
});
When using JS to access the API your API_KEY is going to be there on the page in clear text.Maybe this stuff should be done on the server side.
回答2:
After a little research, it doesn't look like Asana's API supports returning JSONP right now.
Additionally, after some probing of my own, it doesn't look like they support CORS either, so cross-origin XHRs look out of the question. Granted, I didn't test with proper authentication, and their service may be configured to only grant CORS headers to requests that are authorized.
You can, alternatively, have a server-side script issue a generic web request to the API and proxy the results back to your UI.
来源:https://stackoverflow.com/questions/11280001/retrieve-restful-data-using-jquery-ajax-method