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 = new HttpClient();
  try {
    final xhr = await client.openUrl(method, url);
    if (headers != null) {
      final xhrheaders = xhr.headers;
      headers.forEach(xhrheaders.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))) {
      resp.listen(_ignore).asFuture().catchError(_voidCatch);
        //need to pull out response.body. Or, it will never ends (memory leak)
      return null;
    }

    final result = <int>[];
    await resp.listen(result.addAll).asFuture();
    return result;
  } finally {
    InvokeUtil.invokeSafely(client.close);
  }
}