In the browser, Ajax
achieves data transmission through the XMLHttpRequest
object.
Before making an HTTP
request, the XMLHttpRequest
object must be initialized through the open
method. open
takes five parameters: request method, request URL, asynchronous flag, username, and password for server-side authentication.
After successfully initializing the request, the setRequestHeader
method of the XMLHttpRequest
object can be used to set the request header.
After calling the open()
method, the request can be sent with the send()
method according to the parameters set by the open
method.
When the open
method is set to send the request asynchronously, the onreadystatechange
event listener will be automatically triggered when the readyState
property of the XMLHttpRequest
object changes.
If the readyState
property of the XMLHttpRequest
object has not yet become 4
, abort
can be used to terminate the request. This method ensures that callbacks in asynchronous requests are not executed.
Due to the browser's same-origin policy (where different protocols, URLs
, or port numbers are considered cross-origin requests), this code needs to be executed directly in the Console
of the developer tools while opening the homepage of Baidu and checking the effect in Network
.