If content-type is not passed, application/x-www-form-urlencoded will be used when you pass data as a query string.
Passing data as object, application/json will be automatically used (since v3.0.0).
Note about uploads:
If you need to upload some file, with FormData, use content-type: null.
baseUrl
You can pass a baseUrl param to improve calls. Example:
constrequest=ajax({baseUrl: 'http://example.com/api/v2'})request.get('/users')// get `http://example.com/api/v2/users` url
Methods
You may use any of this methods, instead the above approach:
get(url, [data])
Get data as a JSON object.
ajax().get('/api/users')
You can pass data on get method, that will be added on URL as query string:
ajax().get('/api/users',{id: 1})
It will request on /api/users?id=1.
post(url, [data])
Save a new register or update part of this one.
// Without headersajax().post('/api/users',{slug: 'john'})// With headersvarrequest=ajax({headers: {'x-access-token': '123@abc'}})request.post('/login',{username: 'user',password: 'b4d45$'})
Disclaimer: these return methods are not from real Promises, and they will just being called once.
If you want to work with real Promises, you should make your own abstraction.
then(response, xhrObject)
Promise that returns if the request was successful.
ajax().get('/api/users').then(function(response,xhr){// Do something})
catch(responseError, xhrObject)
Promise that returns if the request has an error.
ajax().post('/api/users',{slug: 'john'}).catch(function(response,xhr){// Do something})
always(response, xhrObject)
That promise always returns, independent if the status is done or error.
ajax().post('/api/users',{slug: 'john'}).always(function(response,xhr){// Do something})
Abort request
If a request is very slow, you can abort it using abort() method:
请发表评论