XMLHTTPRequest object details
1. In Ajax applications, we use the XMLHTTPRequest object to send requests asynchronously. Such requests can be both get and post requests with request parameters.
After the request is sent out, the server response will be returned when appropriate, but the client will not automatically load this asynchronous response. The program must first call the responsetext or responsexml of the XMLHTTPRequest object to obtain the server response, then, the server response is dynamically loaded to the current page through the DOM operation.
XMLHttpRequest is used to provide asynchronous communication with the server.
2. Basic Methods for XMLHttpRequest objects:
Abort (): stops sending the current request.
GetAllResponseHeaders (): Get all Response Headers returned by the server
Getresponseheaders ("headerlabel"): obtains the corresponding response header based on the response header name.
Request. Open (method, URL, async, username, password) Establish a URL link with the server
Send (content): send a request. Content is the request parameter.
SetRequestHeader ("label", "value") sets the request header before sending a request
3. Basic Attributes of XMLHttpRequest:
Onreadystatechange: Specifies the event handler function when the XMLHTTPRequest object state changes.
Readystate: processing status of the XMLHTTPRequest object
Responsetext: Get the response text of the server
Responsexml: Get the XML Document Object of the server response
Status: Status Code returned by the server. This status code is available only when the server response is complete.
Statustext: text information about the status returned by the server
Routine:
<Body> <select name = "first" id = "first" size = "3" onchange = "Change (this. value ); "> <option value =" 1 "selected =" selected "> China </option> <option value =" 2 "> USA </option> <option value =" 3"> Japan </option> </SELECT> <select id = "second" size = "3"> </SELECT> <HR/> <Div id = "output1"> </div> <Div id = "output2"> </div> <SCRIPT type = "text/JavaScript"> Function Change (ID) {var request = new XMLHttpRequest (); var url = "/ajax/second. JSP? Id = "+ ID; request. open ("Post", URL, true); // you can specify the request header. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); // sets the callback function request for processing the response. onreadystatechange = function processresponse () {// test the processing status of the XMLHTTPRequest object. readystate attributes // alert (request. readystate); If (request. readystate = 4) {If (request. status = 200 | request. status = 304) {var headers = request. getAllResponseHeaders (); // alert ("Request Header type: "+ typeof headers +" \ n "+ headers); // output all request headers in the document. getelementbyid ("output1 "). innerhtml = headers; document. getelementbyid ("output2 "). innerhtml = request. responsetext; var citylist = request. responsetext. split ("$"); var displayselect = document. getelementbyid ("second"); displayselect. innerhtml = NULL; For (VAR I = 0; I <citylist. length; I ++) {var option = document. createelement ("option"); option. innerhtml = Citylist [I]; displayselect. appendchild (option) ;}} else {window. Alert ("the page you requested has an exception! ") ;}} Request. send (null) ;}</SCRIPT> </body> code embedded in the JSP page: <% int id = integer. parseint (request. getparameter ("ID"); system. out. println (ID); Switch (ID) {Case 1: %> Shanghai $ Guangzhou $ Beijing <% break; Case 2: %> Washington $ New York $ California <% break; case 3: %> Tokyo $ Osaka $ Nagoya <% break;} %>
4. steps followed by XMLHttpRequest:
1. initialize the XMLHTTPRequest object
2. Open the connection to the server
3. Set the event function for listening to XMLHttpRequest status changes.
4. Send a request
5. Generally, GET requests are used to obtain data from the server, and post requests are used to send data to the server.
The GET request converts all request parameters into a query string and adds the string to the request URL
If the action attribute of a form is set to get, the request will convert the values of each field in the form into strings and append them to the URL.
The post request uses the http post mechanism to transmit the request parameters and corresponding values in the HTML header.
The size of the GET request transmitted is small, generally not greater than 2 kb. The size of the POST request parameter is not limited, but usually depends on the server limit.
When Ajax is used to send asynchronous requests, post requests are recommended.
6. Chinese garbled characters
Use post submission normally (post requests use the UTF-8 character set by default to encode request parameters) and add on the JSP page (sometimes not, because some server pages are encoded as UTF-8 by default) setcharacterencoding
("UTF-8"); there should be no garbled characters.
If a GET request is submitted using get, the request parameters and corresponding values are appended to the request URL. The parameter values for Chinese requests are no longer transmitted in Chinese, instead, it must be transcoded to the URL format, so it must be processed on the server side as follows: Assuming the server side obtains the target parameter, first obtains the value request parameter, and then encodes it into a byte array according to the ISO-8859-1 character set, the byte array is then decoded into a string by the UTF-8 character set.
String target = request. getparameter ("value ");
String A = new string (target. getbytes ("ISO-8859-1"), "UTF-8 ");
// The preceding get method cannot be easily handled, because different browsers may use different character sets to encode GET request parameters, so try to use post to submit
7. Send XML requests
HTML code: <body> <select name = "first" id = "first" style = "width: 80px; "size =" 3 "multiple =" multiple "> <option value =" 1 "> China </option> <option value =" 2 "> us </option> <Option value = "3"> Japan </option> </SELECT> <input type = "button" value = "Send request" onclick = "Send (); "> <select name =" second "id =" second "style =" width: 100px; "size =" 6 "> </SELECT> <SCRIPT type =" text/JavaScript "> // defines the function createxml () {var X for creating an XML document ML = "<countrys>"; var Options = document. getelementbyid ("first "). childnodes; var option = NULL; For (VAR I = 0; I <options. length; I ++) {Option = options [I]; If (option. selected) {XML + = "<country>" + option. value + "<\/country>" ;}// end the root node XML + = "<\/countrys>"; return XML;} function send () {var request = new XMLHttpRequest (); var url = "/ajax/XML. JSP "; request. open ("Post", URL, true); Request. onreadystatechange = Fu Nction () {// test the processing status readystate attribute of the XMLHTTPRequest object // alert (request. readystate); If (request. readystate = 4) {If (request. status = 200 | request. status = 304) {var headers = request. getAllResponseHeaders (); // alert ("Request Header type:" + typeof headers + "\ n" + headers ); // output all request headers var citylist = request. responsetext. split ("$"); var displayselect = document. getelementbyid ("second"); displayselect. innerhtml = NULL; (VaR I = 0; I <citylist. length; I ++) {var option = document. createelement ("option"); option. innerhtml = citylist [I]; displayselect. appendchild (option) ;}} else {window. alert ("the page you requested is abnormal! ") ;}} Request. send (createxml () ;}</SCRIPT> </body> JSP embedded code: <% // defines a stringbuffer object, used for request parameter stringbuffer xmlbuffer = new stringbuffer (); string line = NULL; // obtain the input stream bufferedreader reader = request through the request object. getreader (); While (line = reader. readline ())! = NULL) {xmlbuffer. append (line);} string xml = xmlbuffer. tostring (); // dom4j parses the XML string document xmldoc = new xppreader (). read (New bytearrayinputstream (XML. getbytes (); // obtain the list countrylist = xmldoc of all subnodes of the countrys node. getrootelement (). elements (); // defines the server response result string result = ""; // traverses all nodes for (iterator it = countrylist. iterator (); it. hasnext ();) {element Country = (element) it. next (); If (country. gettext (). equals ("1") {result + = "$ Shanghai $ Guangzhou $ Beijing";} else if (country. gettext (). equals ("2") {result + = "$ Washington $ New York $ Silicon Valley";} else if (country. gettext (). equals ("3") {result + = "$ Tokyo $ Osaka $ Nagoya" ;}}// send a response out to the client. println (result); %>
From the code above, we can see that the XML request sent is still a POST request, but the request parameter is not sent in the form of param = value, but directly uses the XML string as the parameter.
This means that the server cannot directly obtain request parameters, but must obtain Request Parameters in the form of a stream.
8. When using XML to respond to client requests, pay attention to the differences between different browsers. Although various browsers have implemented DOM specifications, there are still some differences in details. The returned XML document object must be supported by the XML Parser of the browser.
9. Running cycle of the XMLHTTPRequest object
(1) Ajax applications always start from creating XMLHttpRequest objects. The function of XMLHttpRequest, as its name implies, allows HTTP requests to be sent through client scripts, the first step of an Ajax application is to always create an XMLHttpRequest instance and use it to send requests and get/POST requests.
(2) When will the server response arrive after XMLHttpRequest is sent? When should I handle the server response? This requires the JS event mechanism. XMLHttpRequest is also a common JS object. Like a common button or text box, it can trigger an event: the event triggered by XMLHttpRequest is onreadystatechange. when the status of the XMLHTTPRequest object changes, the onreadystatechange event is triggered. Specify an event handler for the onreadystatechange attribute of the XMLHTTPRequest object. This event handler can be triggered when the XMLHttpRequest status changes. This event handler is also called a callback function.
(3) When the XMLHttpRequest status changes and the readystate is 4, the server response is completed and the server response can be processed.
(4) Through the JS event mechanism, the event processing function is used to listen for changes in the XMLHttpRequest status. When the readystate of XMLHttpRequest is 4 and the status is 200, the event processing function processes the server response.
(5) After Entering the event processing function, the XMLHTTPRequest object is indispensable. The event processing function needs to use the XMLHTTPRequest object to obtain the server response, and call the responsetext or responsexml method to obtain the server response. So far, the running cycle of the XMLHTTPRequest object has ended.
(6) JavaScript dynamically loads server responses to HTML pages through DOM operations.