Class: SC.Request


Extends SC.Copyable, SC.Freezable, SC.Object.

Implements support for Ajax requests using XHR, XHR 2 and other protocols.

SC.Request is much like an inverted version of the request/response objects you receive when implementing HTTP servers.

To send a request, you just need to create your request object, configure your options, and call send() to initiate the request.

Defined in: request.js.

Field Summary

Class Methods

Instance Methods

Field Detail

String address
The URL this request to go to.
Default Value:
null
Boolean attachIdentifyingHeaders

Specifies whether or not the request will have custom headers attached to it. By default, SC.Request attaches X-Requested-With and X-SproutCore-Version headers to all outgoing requests. This allows you to override that behavior.

You may want to set this to NO if you are making simple CORS requests in compatible browsers. See CORS Spec for more information.

TODO: Add unit tests for this feature

Default Value:
YES
Object|String body

The body of the request. May be an object is isJSON or isXML is set, otherwise should be a string.

Default Value:
null
Object|String encodedBody
The body, encoded as JSON or XML if needed.
Default Value:
#body
Hash headers
Current set of headers for the request
Boolean isAsynchronous

Sends the request asynchronously instead of blocking the browser. You should almost always make requests asynchronous. You can change this options with the async() helper option (or simply set it directly).

Default Value:
YES
Boolean isJSON

Processes the request and response as JSON if possible. You can change this option with the json() helper method.

Default Value:
NO
Boolean isXML

Process the request and response as XML if possible. You can change this option with the xml() helper method.

Default Value:
NO
SC.Response responseClass

Underlying response class to actually handle this request. Currently the only supported option is SC.XHRResponse which uses a traditional XHR transport.

Default Value:
SC.XHRResponse
source
The original request for copied requests.
Default Value:
null
Number timeout

An optional timeout value of the request, in milliseconds. The timer begins when SC.Response#fire is actually invoked by the request manager and not necessarily when SC.Request#send is invoked. If this timeout is reached before a response is received, the equivalent of SC.Request.manager#cancel() will be invoked on the SC.Response instance and the didReceive() callback will be called.

An exception will be thrown if you try to invoke send() on a request that has both a timeout and isAsyncronous set to NO.

Default Value:
null
String type
The HTTP method to use.
Default Value:
'GET'

Class Method Detail

deleteUrl
Helper method for quickly setting up a DELETE request.
Parameters:
String address
url of request
Returns:
SC.Request receiver
getUrl
Helper method for quickly setting up a GET request.
Parameters:
String address
url of request
Returns:
SC.Request receiver
patchUrl
Helper method for quickly setting up a PATCH request.
Parameters:
String address
url of request
String body
Returns:
SC.Request receiver
postUrl
Helper method for quickly setting up a POST request.
Parameters:
String address
url of request
String body
Returns:
SC.Request receiver
putUrl
Helper method for quickly setting up a PUT request.
Parameters:
String address
url of request
String body
Returns:
SC.Request receiver

Instance Method Detail

async
Converts the current request to be asynchronous.
Parameters:
Boolean flag
YES to make asynchronous, NO or undefined. Default YES.
Returns:
SC.Request receiver
clearHeaders

Clears the list of headers that were set on this request. This could be used by a subclass to blow-away any custom headers that were added by the super class.

copy

Returns a copy of the current request. This will only copy certain properties so if you want to add additional properties to the copy you will need to override copy() in a subclass.

Returns:
SC.Request new request
didReceive

Invoked after a response has been processed but before any listeners are notified. You can do any standard processing on the request at this point. If you don't want to allow notifications to continue, call response.cancel()

Parameters:
SC.Request request
A copy of the request object, frozen
SC.Response response
The object that will wrap the response
didSend

Invoked on the original request object just after the request is sent to the server. You might use this callback to update some state in your application.

The passed request is a frozen copy of the request, indicating the options set at the time of the request.

Parameters:
SC.Request request
A copy of the request object, frozen
SC.Response response
The object that will wrap the response
Returns:
Boolean YES on success, NO on failure
header

To set headers on the request object. Pass either a single key/value pair or a hash of key/value pairs. If you pass only a header name, this will return the current value of the header.

Parameters:
String|Hash key
String value
Returns:
SC.Request|Object receiver
json
Converts the current request to use JSON.
Parameters:
Boolean flag
YES to make JSON, NO or undefined. Default YES.
Returns:
SC.Request receiver
notify

Configures a callback to execute as a request progresses or completes. You must pass at least a target and action/method to this and optionally an event name or status code.

You may also pass additional arguments which will then be passed along to your callback.

Scoping With Status Codes

If you pass a status code as the first argument to this method, the accompanying notification callback will only be called if the response status matches the status code. For example, if you pass 201 (or SC.Request.CREATED), the accompanying method will only be called if the response status from the server is also 201.

You can also pass "generic" status codes such as 200, 300, or 400, which will be invoked anytime the status code is in the same range and if a more specific notifier was not registered first and returned YES.

Finally, passing a status code of 0 or no status at all will cause your method to be executed no matter what the resulting status is unless a more specific notifier was registered first and returned YES.

For example,

var req = SC.Request.create({type: 'POST'});
req.notify(201, this, this.reqWasCreated);  // Handle a specific status code
req.notify(401, this, this.reqWasUnauthorized);  // Handle a specific status code
req.notify(400, this, this.reqDidRedirect);  // Handle any 4xx status
req.notify(this, function(response, arg1, arg2) {
  // do something
}, arg1, arg2);  // Handle any status.  Also, passing additional arguments to the callback handler

Notifying on Progress Events

If you pass a progress event name your callback will be called each time the event fires on the response. For example, the XMLHttpRequest Level 2 specification defines several progress events: loadstart, progress, abort, error, load, timeout and loadend. Therefore, when using the default SC.Request responseClass, SC.XHRResponse, you can be notified of each of these events by simply providing the matching event name.

Note that many older browsers do not support XMLHttpRequest Level 2. See http://caniuse.com/xhr2 for a list of supported browsers.

For example,

var req = SC.Request.create({type: 'GET'}); req.notify('progress', this, this.reqDidProgress); // Handle 'progress' events req.notify('abort', this, this.reqDidAbort); // Handle 'abort' events req.notify('upload.progress', this, this.reqUploadDidProgress); // Handle 'progress' events on the XMLHttpRequestUpload req.send();

Callback Format

Your notification callback should expect to receive the Response object as the first parameter for status code notifications and the Event object for progress notifications; plus any additional parameters that you pass. If your callback handles the notification and to prevent further handling, it should return YES.

Parameters:
statusOrEvent Optional
{Number|String} A Number status code or String Event name.
target
{Object} The target object for the callback action.
action
{String|Function} The method name or function to call on the target.
Returns:
SC.Request The SC.Request object.
resend

Resends the current request. This is more efficient than calling send() for requests that have already been used in a send. Otherwise acts just like send(). Does not take a body argument.

Returns:
SC.Response new response object
send

Will fire the actual request. If you have set the request to use JSON mode then you can pass any object that can be converted to JSON as the body. Otherwise you should pass a string body.

Parameters:
String|Object body Optional
Returns:
SC.Response New response object
timeoutAfter
Sets the maximum amount of time the request will wait for a response.
Parameters:
Number timeout
The timeout in milliseconds.
Returns:
SC.Request receiver
willReceive

Invoked when a response has been received but not yet processed. This is your chance to fix up the response based on the results. If you don't want to continue processing the response call response.cancel().

Parameters:
SC.Request request
A copy of the request object, frozen
SC.Response response
The object that will wrap the response
willSend

Invoked on the original request object just before a copied request is frozen and then sent to the server. This gives you one last change to fixup the request; possibly adding headers and other options.

If you do not want the request to actually send, call cancel().

Parameters:
SC.Request request
A copy of the request object, not frozen
SC.Response response
The object that will wrap the response
xml
Converts the current request to use XML.
Parameters:
Boolean flag
YES to make XML, NO or undefined. Default YES.
Returns:
SC.Request recevier
Documentation generated by JsDoc Toolkit 2.4.0 on Thu Apr 11 2013 16:14:36 GMT+0800 (CST)