Class XMLHttpRequest
- Namespace
- CSharpToJavaScript.APIs.JS
- Assembly
- CSharpToJavaScript.dll
XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.
[Value("XMLHttpRequest")]
public class XMLHttpRequest : XMLHttpRequestEventTarget
- Inheritance
-
XMLHttpRequest
- Inherited Members
Remarks
Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.
If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the EventSource interface. For full-duplex communication, WebSockets may be a better choice.
-XMLSerializer: Serializing a DOM tree into XML
-Using XMLHttpRequest
-Fetch API
Constructors
XMLHttpRequest()
The XMLHttpRequest() constructor
creates a new XMLHttpRequest.
public XMLHttpRequest()
Remarks
Fields
DONE
[Value("DONE")]
public const ushort DONE = 4
Field Value
HEADERS_RECEIVED
[Value("HEADERS_RECEIVED")]
public const ushort HEADERS_RECEIVED = 2
Field Value
LOADING
[Value("LOADING")]
public const ushort LOADING = 3
Field Value
OPENED
[Value("OPENED")]
public const ushort OPENED = 1
Field Value
UNSENT
[Value("UNSENT")]
public const ushort UNSENT = 0
Field Value
Properties
Onreadystatechange
[Value("onreadystatechange")]
public EventHandlerNonNull Onreadystatechange { get; set; }
Property Value
ReadyState
The XMLHttpRequest.readyState property returns the state an XMLHttpRequest client is in. An XHR client exists in one of the following states:
[Value("readyState")]
public ushort ReadyState { get; }
Property Value
Remarks
Value | State | Description |
|
| Client has been created. |
|
|
|
|
|
|
|
| Downloading; |
|
| The operation is complete. |
Response
The XMLHttpRequestresponse property returns the response's body content as
an {{jsxref("ArrayBuffer")}}, a Blob, a Document,
a JavaScript Object, or a string, depending on the value
of the request's ResponseType
property.
[Value("response")]
public dynamic Response { get; }
Property Value
- dynamic
An appropriate object based on the value of ResponseType.
You may attempt to request the data be provided in a specific format
by setting the value ofresponseTypeafter calling
Open(string, string) to initialize the request but before
calling Send(Union236?) to send the request to the server.The value isnullif the request is not yet complete or was unsuccessful,
with the exception that when reading text data using aresponseTypeof"text"or the empty string (""), the response can contain the
response so far while the request is still in theLOADING
ReadyState (3).
Remarks
-Using XMLHttpRequest
-Getting text and HTML/XML data: ResponseText and
ResponseXML
ResponseText
The read-only XMLHttpRequest propertyresponseText returns the text received from a server
following a request being sent.
[Value("responseText")]
public string ResponseText { get; }
Property Value
- string
A string which contains either the textual data received using the
XMLHttpRequestor""if the request failed or if no content has been received yet.While handling an asynchronous request, the value ofresponseTextalways
has the current content received from the server, even if it's incomplete because the
data has not been completely received yet.You know the entire content has been received when the value of
ReadyState becomesXMLHttpRequest.DONE(4), and
Status becomes 200 ("OK").
Remarks
ResponseType
The XMLHttpRequest propertyresponseType is an enumerated string value specifying
the type of data contained in the response.
[Value("responseType")]
public XMLHttpRequestResponseType ResponseType { get; set; }
Property Value
- XMLHttpRequestResponseType
A string which specifies what type of data the response contains.
It can take the following values:NOTE
When settingresponseTypeto a particular value, the author should make
sure that the server is actually sending a response compatible with that format. If
the server returns data that is not compatible with theresponseTypethat
was set, the value of Response will benull.
Remarks
It also lets the author change the
response type. If an empty string is set as the value of responseType, the
default value of text is used.
-Using XMLHttpRequest
-HTML in XMLHttpRequest
-The response data: Response,
ResponseText, and
ResponseXML
ResponseURL
The read-only XMLHttpRequest.responseURL property returns the serialized URL of the response or the empty string if the URL is null. If the URL is returned, any URL fragment present in the URL will be stripped away. The value of responseURL will be the final URL obtained after any redirects.
[Value("responseURL")]
public string ResponseURL { get; }
Property Value
Remarks
ResponseXML
The XMLHttpRequest.responseXML read-only property returns
a Document containing the HTML or XML retrieved by the request; ornull if the request was unsuccessful, has not yet been sent, or if the data
can't be parsed as XML or HTML.
[Value("responseXML")]
public Document? ResponseXML { get; }
Property Value
- Document
A Document from parsing the XML or HTML received using
XMLHttpRequest, ornullif no data was received or if the
data is not XML/HTML.
Remarks
NOTE
The name
responseXMLis an artifact of this
property's history; it works for both HTML and XML.
Usually, the response is parsed as "text/xml". If the
ResponseType is set to"document" and the request was made asynchronously, instead the response is
parsed as "text/html". responseXML is null for
any other types of data, as well as for data: URLs.
If the server doesn't specify the Content-Type as"text/xml" or "application/xml", you can use
OverrideMimeType(string) to parse it as XML anyway.
This property isn't available to workers.
-XMLHttpRequest
-Response
-ResponseType
-Parsing and serializing XML
-Parsing XML into a DOM tree: DOMParser
-Serializing a DOM tree into XML: XMLSerializer (specifically, the
SerializeToString(Node) method)
Status
The read-only XMLHttpRequest.status property returns the numerical HTTP status code of the XMLHttpRequest's response.
[Value("status")]
public ushort Status { get; }
Property Value
- ushort
A number.
Remarks
Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors.
-List of HTTP status
-HTTP
StatusText
The read-only XMLHttpRequest.statusText property returns a string containing the response's status message as returned by the HTTP server. Unlike XMLHttpRequest.status which indicates a numerical status code, this property contains the text of the response status, such as "OK" or "Not Found". If the request's readyState is in UNSENT or OPENED state, the value of statusText will be an empty string.
[Value("statusText")]
public string StatusText { get; }
Property Value
- string
A string.
Remarks
If the server response doesn't explicitly specify a status text, statusText will assume the default value "OK".
NOTE
Responses over an HTTP/2 connection will always have an empty string as status message as HTTP/2 does not support them.
-List of HTTP status
-HTTP
-WHATWG Fetch Living Standard
Timeout
The XMLHttpRequest.timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. Timeout shouldn't be used for synchronous XMLHttpRequests requests used in a 'document environment' or it will throw an InvalidAccessError exception. When a timeout happens, a timeout event is fired.
[Value("timeout")]
public ulong Timeout { get; set; }
Property Value
Remarks
NOTE
You may not use a timeout for synchronous requests with an owning window.
Upload
The XMLHttpRequest upload property returns an XMLHttpRequestUpload object that can be observed to monitor an upload's progress.
[Value("upload")]
public XMLHttpRequestUpload Upload { get; }
Property Value
Remarks
It is an opaque object, but because it's also an XMLHttpRequestEventTarget, event listeners can be attached to track its process.
NOTE
Attaching event listeners to this object prevents the request from being a "simple request" and will cause a preflight request to be issued if cross-origin; see CORS. Because of this, event listeners need to be registered before calling Send(Union236?) or upload events won't be dispatched.
NOTE
The spec also seems to indicate that event listeners should be attached after Open(string, string). However, browsers are buggy on this matter, and often need the listeners to be registered before Open(string, string) to work.
The following events can be triggered on an upload object and used to monitor the upload:
WithCredentials
The XMLHttpRequest.withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authentication headers or TLS client certificates. Setting withCredentials has no effect on same-origin requests.
[Value("withCredentials")]
public bool WithCredentials { get; set; }
Property Value
- bool
A boolean.
Remarks
In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is false. XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.
NOTE
This never affects same-origin requests.
NOTE
XMLHttpRequestresponses from a different domain cannot set cookie values for their own domain unlesswithCredentialsis set totruebefore making the request, regardless ofAccess-Control-header values.
Methods
Abort()
The XMLHttpRequest.abort() method aborts the request if
it has already been sent. When a request is aborted, its
ReadyState is changed toXMLHttpRequest.UNSENT (0) and the request's
Status code is set to 0.
[Value("abort")]
public GlobalObject.Undefined Abort()
Returns
Remarks
If the request is still in progress (its readyState is not XMLHttpRequest.DONE or XMLHttpRequest.UNSENT), a XMLHttpRequestreadystatechange event, XMLHttpRequestEventTargetabort, and a XMLHttpRequestEventTargetloadend event are dispatched, in that order. For synchronous requests, no events are dispatched and an error is thrown instead.
GetAllResponseHeaders()
The XMLHttpRequest methodgetAllResponseHeaders() returns all the response
headers, separated by 'CRLF', as a string, or returns null
if no response has been received.
[Value("getAllResponseHeaders")]
public string GetAllResponseHeaders()
Returns
- string
A string representing all of the response's headers (except those
whose field name isSet-Cookie) separated by 'CRLF',
ornullif no response has been received. If a network error
happened, an empty string is returned.An example of what a raw header string looks like:Each line is terminated by both carriage return and line feed characters
(\r\n). These are essentially delimiters separating each of the headers.NOTE
In modern browsers, the header names are returned in all lower
case, as per the latest spec.
Remarks
If a network error happened, an empty string
is returned.
NOTE
For multipart requests, this returns the headers from the
current part of the request, not from the original channel.
-Using XMLHttpRequest
-Setting request headers: SetRequestHeader(string, string)
GetResponseHeader(string)
The XMLHttpRequest methodgetResponseHeader() returns the string containing the
text of a particular header's value.
[Value("getResponseHeader")]
public string? GetResponseHeader(string name)
Parameters
namestring
Returns
- string
A string representing the header's text value, or
null
if either the response has not yet been received or the header doesn't exist in the
response.
Remarks
If there are multiple response headers
with the same name, then their values are returned as a single concatenated string,
where each value is separated from the previous one by a pair of comma and space. ThegetResponseHeader() method returns the value as a UTF byte sequence.
NOTE
The search for the header name is case-insensitive.
If you need to get the raw string of all of the headers, use the
GetAllResponseHeaders() method,
which returns the entire raw header string.
-Using XMLHttpRequest
-HTTP headers
-GetAllResponseHeaders()
-Response
-Setting request headers: SetRequestHeader(string, string)
Open(string, string)
The XMLHttpRequest method open()
initializes a newly-created request, or re-initializes an existing one.
[Value("open")]
public GlobalObject.Undefined Open(string method, string url)
Parameters
Returns
Remarks
NOTE
Calling this method for an already active request
(one for whichopen()has already been called) is the equivalent of calling
Abort().
-Using XMLHttpRequest
-Related XMLHttpRequest methods:
SetRequestHeader(string, string),
Send(Union236?), and
Abort()
Open(string, string, bool, string?, string?)
The XMLHttpRequest method open()
initializes a newly-created request, or re-initializes an existing one.
[Value("open")]
public GlobalObject.Undefined Open(string method, string url, bool async, string? username = null, string? password = null)
Parameters
Returns
Remarks
NOTE
Calling this method for an already active request
(one for whichopen()has already been called) is the equivalent of calling
Abort().
-Using XMLHttpRequest
-Related XMLHttpRequest methods:
SetRequestHeader(string, string),
Send(Union236?), and
Abort()
OverrideMimeType(string)
The XMLHttpRequest methodoverrideMimeType() specifies a MIME type other than the
one provided by the server to be used instead when interpreting the data being
transferred in a request.
[Value("overrideMimeType")]
public GlobalObject.Undefined OverrideMimeType(string mime)
Parameters
mimestring
Returns
Remarks
This may be used, for example, to force a stream to
be treated and parsed as "text/xml", even if the server does not report it
as such. This method must be called before calling Send(Union236?).
Send(Union236?)
The XMLHttpRequest methodsend() sends the request to the server.
[Value("send")]
public GlobalObject.Undefined Send(Union236? body = null)
Parameters
bodyUnion236?
Returns
Remarks
If the
request is asynchronous (which is the default), this method returns as soon as the
request is sent and the result is delivered using events. If the request is synchronous,
this method doesn't return until the response has arrived.
send() accepts an optional parameter which lets you specify the request's
body; this is primarily used for requests such as PUT. If the request
method is GET or HEAD, the body
parameter is ignored and the request body is set to null.
If no Accept header has been set using the
SetRequestHeader(string, string), anAccept header with the type "*/*" (any type) is sent.
SetAttributionReporting(AttributionReportingRequestOptions)
NOTE
ExperimentalsetAttributionReporting() method of theXMLHttpRequest interface indicates that you want the request's response to be able to register a JavaScript-based attribution source or attribution trigger.
[Value("setAttributionReporting")]
public GlobalObject.Undefined SetAttributionReporting(AttributionReportingRequestOptions options)
Parameters
Returns
- GlobalObject.Undefined
None (
undefined).
Remarks
SetPrivateToken(PrivateToken)
[Value("setPrivateToken")]
public GlobalObject.Undefined SetPrivateToken(PrivateToken privateToken)
Parameters
privateTokenPrivateToken
Returns
SetRequestHeader(string, string)
The XMLHttpRequest method setRequestHeader() sets the value of an HTTP request header.
When using setRequestHeader(), you must call it after calling Open(string, string), but before calling Send(Union236?).
If this method is called several times with the same header, the values are merged into one single request header.
[Value("setRequestHeader")]
public GlobalObject.Undefined SetRequestHeader(string name, string value)
Parameters
Returns
Remarks
Each time you call setRequestHeader() after the first time you call it, the specified text is appended to the end of the existing header's content.
If no Accept header has been set using this, an Accept header with the type "*/*" is sent with the request when Send(Union236?) is called.
For security reasons, there are several Forbidden_request_header whose values are controlled by the user agent. Any attempt to set a value for one of those headers from frontend JavaScript code will be ignored without warning or error.
In addition, the Authorization HTTP header may be added to a request, but will be removed if the request is redirected cross-origin.
NOTE
For your custom fields, you may encounter a "not allowed by Access-Control-Allow-Headers in preflight response" exception when you send requests across domains.
In this situation, you need to set up the Access-Control-Allow-Headers in your response header at server side.