0

In Charles proxy I've captured a successful request made when using curl - which returns some json. I've tried all day to make this into an ajax call but have failed - wonder if someone could take a fresh look at it? I'm sending a token via the header to a service that provides this json

{
"category": [{
    "id": 1,
    "name": "aaa",
    "description": "anything..."
}, {
    "id": 2,
    "name": "ccc",
    "description": "desc 1111..."
}, {
    "id": 3,
    "name": "ddd",
    "description": "desc..."
}]
}

charles dump of the good request made with curl

    GET /api/v1/category HTTP/1.1
    User-Agent  curl/7.30.0
    Host    myurl.com
    Accept  */*
    Authorization   Token token=6ff1fed470ec2ddaf8b3af9584619902

the raw info

    URL http://myurl.com/api/v1/category
    Status  Complete
    Response Code   200 OK 
    Protocol    HTTP/1.1
    Method  GET
    Kept Alive  No
    Content-Type    application/json; charset=utf-8
    Client Address  /127.0.0.1
    Remote Address  myurl.com/23.23.121.64

my attempt

$.ajax({
beforeSend: function (xhr) { xhr.setRequestHeader ('Authorization', 'Token 6ff1fed470ec2ddaf8b3af9584619902') },
type: "GET",
url: "http://myurl.com/api/v1/category",
dataType: "json"
}).done(function( msg ) {
console.log( msg );

}).fail(function(jqXHR, textStatus, errorThrown) {
console.log( "Request failed: " + textStatus );
console.log( errorThrown );
});

thanks in advance!

4

1 回答 1

0

您还没有发布您尝试的诊断信息,所以我只是从您的代码中猜测。

  1. 你发

    Authorization: Token 6ff1fed470ec2ddaf8b3af9584619902

    来自 XHR,但是

    Authorization: Token token=6ff1fed470ec2ddaf8b3af9584619902

    从 curl — 注意token=.

  2. 您必须确保http://myurl.com/api/v1/category支持跨域资源共享或与执行该 JavaScript 代码的页面位于同一来源(域)。

如果这些没有帮助,请发布您收到的任何错误消息。

于 2014-03-01T09:35:47.400 回答