ButuzGOL
ButuzGOL

Reputation: 1243

Get data from $.ajax object

How can I get data from $.ajax Example:

var ajax = $.ajax({
  url: 'http://example.com',
  type: 'GET',
  dataType: 'json'
});

ajax.url // undefined
// But I need
ajax.url // http://example.com

Upvotes: 0

Views: 146

Answers (2)

ButuzGOL
ButuzGOL

Reputation: 1243

It was needed for test so I did this way

  var ajax = $.ajax({
    url: '/signin',
    data: { user: 'ButuzGOL' },
    type: 'POST',
    dataType: 'json'
  });
  ajax.abort();
  ajax.always(function() {
    expect(this.type).to.be('POST');
    expect(this.url).to.be('/signin');
    expect(this.data).to.be({ user: 'ButuzGOL' });

    done();
  });

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

You can't. jqXHR objects, such as ajax, don't have properties for (much of?) the request options in the settings object passed to $.ajax().

But, you can keep settings separately and retrieve request info from it as needed:

var settings = {
  url: 'http://example.com',
  type: 'GET',
  dataType: 'json'
};

var ajax = $.ajax(settings);

console.log(settings.url);

And, if needed, you can attach settings to ajax yourself:

// ...

var ajax = $.ajax(settings);
ajax.settings = settings;
console.log(ajax.settings.url);

Upvotes: 1

Related Questions