XMLHttpRequest
method is also used to post data to a server. Here's an example:
req=new XMLHttpRequest();You've seen several of these methods before. Here the
req.open("POST",url,true);
req.setRequestHeader('Content-Type','text/plain');
req.onreadystatechange=function(){
if(req.readyState==4 && req.status==200){
document.getElementsByClassName('message')[0].innerHTML=req.responseText;
}
};
req.send(userName);
open
method initializes the request as a "POST" to the given URL of the external resource, and uses the true
Boolean to make it asynchronous.
The setRequestHeader
method sets the value of an HTTP request header, which contains information about the sender and the request. It must be called after the open
method, but before the send
method. The two parameters are the name of the header and the value to set as the body of that header.
Next, the onreadystatechange
event listener handles a change in the state of the request. A readyState
of 4 means the operation is complete, and a status
of 200 means it was a successful request. The document's HTML can be updated.
Finally, the send
method sends the request with the userName
value, which was given by the user in the input
field.
XMLHttpRequest
.
testString: 'assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g), ''Your code should create a new XMLHttpRequest
.'');'
- text: Your code should use the open
method to initialize a "POST" request to the server.
testString: 'assert(code.match(/\.open\(\s*?(''|")POST\1\s*?,\s*?url\s*?,\s*?true\s*?\)/g), ''Your code should use the open
method to initialize a "POST" request to the server.'');'
- text: Your code should use the setRequestHeader
method.
testString: 'assert(code.match(/\.setRequestHeader\(\s*?(''|")Content-Type\1\s*?,\s*?(''|")text\/plain\2\s*?\)/g), ''Your code should use the setRequestHeader
method.'');'
- text: Your code should have an onreadystatechange
event handler set to a function.
testString: 'assert(code.match(/\.onreadystatechange\s*?=/g), ''Your code should have an onreadystatechange
event handler set to a function.'');'
- text: Your code should get the element with class message
and change its inner HTML to the responseText
.
testString: 'assert(code.match(/document\.getElementsByClassName\(\s*?(''|")message\1\s*?\)\[0\]\.innerHTML\s*?=\s*?.+?\.responseText/g), ''Your code should get the element with class message
and change its inner HTML to the responseText
.'');'
- text: Your code should use the send
method.
testString: 'assert(code.match(/\.send\(\s*?userName\s*?\)/g), ''Your code should use the send
method.'');'
```
```