ajax jquery简单获取请求

我正在使用jquery ajax进行这个简单的get请求:

$.ajax({ url: "https://app.asana.com/-/api/0.1/workspaces/", type: 'GET', success: function(res) { console.log(res); alert(res); } }); 

结果是返回一个空字符串。 如果我在浏览器中转到此链接,我会得到:

 {"status":401,"error":"Not Authorized"} 

这是预期的结果。 那么为什么不使用ajax呢? 谢谢!

在我看来,这是一个跨域问题,因为您不允许向其他域发出请求。

您必须解决此问题: – 使用代理脚本,在您的服务器上运行,它将提供您的请求,并将处理将其发送到浏览器的响应或 – 您正在请求的服务应该具有JSONP支持。 这是一种跨域技术。 您可能想要阅读此http://en.wikipedia.org/wiki/JSONP

 var dataString = "flag=fetchmediaaudio&id="+id; $.ajax ({ type: "POST", url: "ajax.php", data: dataString, success: function(html) { alert(html); } }); 

您可以向从SAME域和SAME端口加载的应用程序发出AJAX请求。

除此之外,如果希望自动反序列化结果,则应添加dataType JSON

 $.ajax({ url: "https://app.asana.com/-/api/0.1/workspaces/", type: 'GET', dataType: 'json', // added data type success: function(res) { console.log(res); alert(res); } }); 

http://api.jquery.com/jQuery.ajax/

我认为问题是成功函数中没有数据,因为请求在您的情况下因401错误而中断,因此没有成功。

如果你使用

 $.ajax({ url: "https://app.asana.com/-/api/0.1/workspaces/", type: 'GET', error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); 

我认为会有你的401代码( 这个链接是这样说的)

 var settings = { "async": true, "crossDomain": true, "url": "", "method": "GET", "headers": { "content-type": "application/x-www-form-urlencoded" }, "data": { "username": "user@company.com", "password": "12345678" } } $.ajax(settings).done(function (response) { console.log(response); });