Why do we pass null to XMLHttpRequest.send?

前端 未结 4 1538
温柔的废话
温柔的废话 2020-12-15 03:41

Why is send so often called as

xhr.send(null)

instead of

xhr.send()

?

W3, MDN, and M

相关标签:
4条回答
  • 2020-12-15 04:17

    Not adding the null would throw an exception in older versions of Firefox.

    This behavior existed as early as 2002 and existed through Firefox 3 (2008).

    0 讨论(0)
  • 2020-12-15 04:20

    So, if your HTTP request method is GET, then the HTTP client sends data to the server simply by appending it to the request URL (as a so called query string), meaning that the body of the request is gonna stay empty and that is why you need to set the value of that argument to null.

    However, if your HTTP request method is POST, then your request data will be placed into the request body, which will be eventually sent to the server via send function.

    Cheers!

    0 讨论(0)
  • 2020-12-15 04:30

    The XMLHttpRequest.send() method sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. If the request is synchronous, this method doesn't return until the response has arrived. send() accepts an optional argument for the request body. If the request method is GET or HEAD, the argument is ignored and request body is set to null.

    0 讨论(0)
  • 2020-12-15 04:32

    If you'll take a look at an old specification of XMLHttpRequest, it seems like as though the W3C did not require that the parameter be optional at one point, which may have led to people supplying an explicit null value 'just in case'.

    (search for 'SHOULD support the send') http://web.archive.org/web/20060409155734/http://www.w3.org/TR/XMLHttpRequest/

    Another plausible reason I've come across comes from a translation of a russian page, viewable here: long Google Translate link (search for 'GET-Request for Version without ActiveX')

    When you send a GET-request for version without ActiveX, you must specify null, otherwise you can not specify any parameters. Will not fail if GET is always specified null:

    I have no idea if this is true or not but it seems plausible that if the GET parameters were included in the body, that the body may not have been generated if the data value was 'undefined'.

    Unfortunately, I was unable to find anything more conclusive in my search.

    0 讨论(0)
提交回复
热议问题