ajax function

Future<List<int>?> ajax(
  1. Uri url, {
  2. String method = "GET",
  3. List<int>? data,
  4. String? body,
  5. Map<String, String>? headers,
  6. bool? onResponse(
    1. HttpClientResponse response
    )?,
})

Sends an Ajax request to the given url. It returns the data received, or null if error.

To send data in `List

  • onResponse used to retrieve the status code, the response's headers, or force ajax to return the body. Ignored if not specified.

Notice that, by default, ajax returns null if the status code is not between 200 and 299 (see isHttpStatusOK). That is, by default, ajax ignores the body if the status code indicates an error.

If the error description will be in the request's body, you have to specify onResponse with a callback returning true. On the other hand, if onResponse returns false, ajax will ignore the body, and returns null. If onResponse returns null, it is handled as default (as described above).

Implementation

Future<List<int>?> ajax(Uri url, {String method = "GET",
    List<int>? data, String? body, Map<String, String>? headers,
    bool? onResponse(HttpClientResponse response)?}) async {
  final client = HttpClient();
  try {
    final xhr = await client.openUrl(method, url);
    headers?.forEach(xhr.headers.add);

    if (data != null) xhr.add(data);
    if (body != null) xhr.write(body);

    final resp = await xhr.close(),
      statusCode = resp.statusCode;

    if (!(onResponse?.call(resp) ?? isHttpStatusOK(statusCode))) {
      // Always discard the body so the connection can finish cleanly.
      await resp.drain();
      return null;
    }

    // Read the whole body.
    final result = BytesBuilder(copy: false);
    await for (final chunk in resp) {
      result.add(chunk);
    }
    return result.takeBytes();

  } finally {
    InvokeUtil.invokeSafely(client.close);
  }
}