retrieve RESTful data using JQuery ajax() method

时光毁灭记忆、已成空白 提交于 2019-12-13 02:56:53

问题


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

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