使用JQuery ajax()方法检索RESTful数据 [英] retrieve RESTful data using JQuery ajax() method

查看:243
本文介绍了使用JQuery ajax()方法检索RESTful数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过JQuery.ajax()方法从Asana API提取信息.但是没有返回期望的结果,也没有显示错误.
这是我在JavaScript中的部分代码:

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);

                    }
                });
        });

    });

我已经阅读了很多有关ajax()方法的内容,但是仍然想出了该方法中的一些选项参数,例如data,dataType(因为这是跨域请求,因此我使用了jsonp).
有人可以帮忙成功地从Asana API提取信息吗?

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?

推荐答案

即使Asana API当前似乎不支持JSONP,如果将来它们支持并且您需要进行身份验证,也可以使用以下方法进行操作代码.

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 + ":"));

  }
);

btoa函数编码为base64,但在所有浏览器中均不支持 如果您需要支持旧版浏览器,则可能需要使用其他一些库.

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.

更新

还可以直接使用jQuery设置用户名,而无需编码或设置标头.

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
 });

使用JS访问API时,您的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.

这篇关于使用JQuery ajax()方法检索RESTful数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆